I want to validate phone numbers like (123) 456-7890 or 1234567890 How should be the \'matches\' condition be written in the following code?
form.validate({
I tried the below solution and it work fine for me.
/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
Tried below phone format:
jQuery.validator.methods.matches = function( value, element, params ) {
var re = new RegExp(params);
// window.console.log(re);
// window.console.log(value);
// window.console.log(re.test( value ));
return this.optional( element ) || re.test( value );
}
rules: {
input_telf: {
required : true,
matches : "^(\\d|\\s)+$",
minlength : 10,
maxlength : 20
}
}
I know this is an old post, but I thought I would share my solution to help others.
This function will work if you want to valid 10 digits phone number "US number"
function getValidNumber(value)
{
value = $.trim(value).replace(/\D/g, '');
if (value.substring(0, 1) == '1') {
value = value.substring(1);
}
if (value.length == 10) {
return value;
}
return false;
}
Here how to use this method
var num = getValidNumber('(123) 456-7890');
if(num !== false){
alert('The valid number is: ' + num);
} else {
alert('The number you passed is not a valid US phone number');
}
Your regex should be something like
[0-9\-\(\)\s]+
.
It matches numbers, dashes, parentheses and space.
If you need something more strict, matching just your example, try this:
([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})
Your code:
rules: {
phoneNumber: {
matches: "[0-9]+", // <-- no such method called "matches"!
minlength:10,
maxlength:10
}
}
There is no such callback function, option, method, or rule called matches
anywhere within the jQuery Validate plugin. (EDIT: OP failed to mention that matches
is his custom method.)
However, within the additional-methods.js file, there are several phone number validation methods you can use. The one called phoneUS
should satisfy your pattern. Since the rule already validates the length, minlength
and maxlength
are redundantly unnecessary. It's also much more comprehensive in that area codes and prefixes can not start with a 1
.
rules: {
phoneNumber: {
phoneUS: true
}
}
DEMO: http://jsfiddle.net/eWhkv/
If, for whatever reason, you just need the regex for use in another method, you can take it from here...
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(\+?1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
This one is work for me:-
/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/