How can i validate phone number using jquery-javascript? Suppose, i want to validate phone number for this textbox
<input type="text" class="phone-number form-control" id="phone-number" />
thanks
Hello, there are several ways to validate your textbox for phone numbers:
$( "#myform" ).validate({
rules: {
phone-number: {
required: true,
phoneUS: true
}
}
});
For using above Validation method, you need to add this script reference with jQuery validate "https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"
function validatePhone(txtPhone) {
var a = document.getElementById(txtPhone).value;
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
}
//it will only allow numeric keys
$(".AllowNumeric").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
var reg = /^((\+44\s?|0)7([45789]\d{2}|624)\s?\d{3}\s?\d{3})$/ ; //UK phone regex
function PhoneValidation(phoneNumber)
{
var OK = reg.exec(phoneNumber);
if (!OK)
window.alert("phone number isn't valid");
else
window.alert("phone number is valid");
}
Fiddle: https://jsfiddle.net/85n1yato/ (Try checking sample number: +447440965338)
var reg = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/; //US regex
function PhoneValidation(phoneNumber)
{
var OK = reg.exec(phoneNumber);
if (!OK)
window.alert("phone number isn't valid");
else
window.alert("phone number is valid");
}
Sample fiddle: https://jsfiddle.net/87hfg201/
Regex to validate phone number
^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d+)\)?)[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?)+)(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$
You can test output here
https://regex101.com/r/Enu3rz/1
OR
You can also use https://github.com/google/libphonenumber library which can be used with Javascript, C#, Java etc.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly