Hi, below is the code to validate the US phone number. In my previous post, I've posted similar code, but here the format is different.
Format: (123)456-7890
I've used jQuery to do this. You have to download the jQuery library code from www.jquery.com and place the script source above the javascript code you use.
aspx:
'< id="txtPhoneNumber" runat="server" maxlength="13">
javascript:
$("#txtPhoneNumber").live("keypress", function(e) {
var keyChar = e.keyCode ? e.keyCode : e.charCode;
if (keyChar <> 57) {
return false;
}
});
$("#txtPhoneNumber").live("keyup", function(e) {
var txtValue = $(this).val();
if ((txtValue.length - 1) == 0) {
txtValue = '(' + txtValue;
}
if (($(this).val().length == 4) && ($(this).val().charAt(3) != ')')) {
txtValue = txtValue + ')';
}
if ($(this).val().length == 8) {
txtValue = txtValue + '-';
}
$(this).val(txtValue);
});
* Validation is done only while typing the phone number
* Only numbers are allowed to type
Quote of the day
Sunday, October 31, 2010
Saturday, October 30, 2010
Formatting TextBox for US Phone number format in Javascript
Follow code can be used to format the textbox which accepts only US Phone numbers. It assigns the hypens automatically after 3 and 3 numbers when the numbers are typed.
Output will be 123-456-7890
aspx:
< id="txtPhone" runat="server" onkeyup="ValidatePhoneUSFormat();" maxlength="12" onkeypress="return AllowOnlyNumbers(event);" onblur="ValidatePhoneUSFormat();">
javascript:
function ValidatePhoneUSFormat() {
var txtValue = document.getElementById('txtPhone').value;
var formatedValue = '';
for (var i = 0; i < i ="="" txtvalue =" txtValue" i ="="" txtvalue =" txtValue" value =" txtValue;" keychar =" e.keyCode"> 57) {
return false;
}
}
Known issues:
1. Code written only while typing the numbers, will update the code when the phone numbers are pasted from clipboard
2. Only numbers are allowed while typing, but allows alphabets while pasting, will update this as well.
Output will be 123-456-7890
aspx:
< id="txtPhone" runat="server" onkeyup="ValidatePhoneUSFormat();" maxlength="12" onkeypress="return AllowOnlyNumbers(event);" onblur="ValidatePhoneUSFormat();">
javascript:
function ValidatePhoneUSFormat() {
var txtValue = document.getElementById('txtPhone').value;
var formatedValue = '';
for (var i = 0; i < i ="="" txtvalue =" txtValue" i ="="" txtvalue =" txtValue" value =" txtValue;" keychar =" e.keyCode"> 57) {
return false;
}
}
Known issues:
1. Code written only while typing the numbers, will update the code when the phone numbers are pasted from clipboard
2. Only numbers are allowed while typing, but allows alphabets while pasting, will update this as well.
Subscribe to:
Posts (Atom)