I want to validate the phone and fax number fields. I want to validate them as phone numbers and fax are given in American format. I have searched but not succeeded. Any one can help how can I validate in following format
Edit
1 (415) xxx xxxx
I want to validate the phone and fax number fields. I want to validate them as phone numbers and fax are given in American format. I have searched but not succeeded. Any one can help how can I validate in following format
Edit
1 (415) xxx xxxx
The best way is to remove all non-digits and then format it into your preferred format yourself.
var raw_number = str.replace(/[^0-9]/g,'');
var regex1 = /^1?([2-9]..)([2-9]..)(....)$/;
if(!regex1.test(raw_number)) {
// is invalid...
} else {
var formatted_number = str.replace(regex1,'1 ($1) $2 $3')
}
That way if they enter 234/555-0123
it will become your preferred format of 1 (234) 555 0123
.
Using regular expressions is fine, I guess, if you are conscienciously limiting your feature to US-formed phone numbers.
However as soon as your code has to deal with international, that method is no longer the most appropriate option. If you have such plans of any kind, and since you are using JavaScript, I suggest that you have a look at Google's libphonenumber.
The following Javascript REGEX validates 123-456-7890 or 123.456.7890 or 1234567890 or 123 456 7890 or (123) 456-7890
^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$
PhoneFormat.com has a javascript library that makes formatting and validating numbers really easy.
Here is one I use (jQuery) for a field validation onBlur:
http://jsfiddle.net/userdude/Ju72W/
jQuery(document).ready(function($){
$cf = $('#customfield_10117');
$cf.blur(function(e){
phone = $(this).val();
phone = phone.replace(/[^0-9]/g,'');
if (phone.length != 10) {
e.preventDefault();
if (confirm('Phone number must include area code and prefix.')) {
setTimeout(function(){$cf.focus()}, 0);
}
} else {
area = phone.substring(0,3);
prefix = phone.substring(3,6);
line = phone.substring(6);
$(this).val('(' + area + ') ' + prefix + '-' + line);
}
});
});
It checks if there were 10 numbers submitted, and then if that is true, reformats to (000) 000-0000 format.
EDIT
A function that uses the same technique (with an added country code qualifier).
http://jsfiddle.net/userdude/Ju72W/1/
jQuery(document).ready(function($){
$cf = $('#customfield_10117');
$cf.blur(function(e){
number = phoneCheckAndFormat(this.value, 11);
if (number === false) {
alert('Entered phone number is not correct.');
return;
}
$(this).val(number);
});
});
function phoneCheckAndFormat(phone, digits) {
phone = phone.replace(/[^0-9]/g,'');
digits = (digits > 0 ? digits : 10);
if (phone.length != digits) {
return false;
} else {
code = '';
if (digits == 11) {
code = '1 ';
phone = phone.substring(1);
}
area = phone.substring(0,3);
prefix = phone.substring(3,6);
line = phone.substring(6);
return code + '(' + area + ') ' + prefix + '-' + line;
}
}