简体   繁体   中英

How to validate phone number using javascript

Having already a script for validate email below

function validateEmail(email){ 
  var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  if(re.test(email)){
    document.getElementById('email').style.borderColor ='#80c75a';
    document.getElementById('emailError').style.display = "none";
    return true;
  }else{
    document.getElementById('email').style.borderColor ='#e35152';
    return false;
  }
}

I need a script that validates a phone number. Can someone help me with this?

First of all you should check if the provided string is a number:

var isPhoneNumber = /^\d+$/.test(val);

Secondly you could check the length:

isPhoneNumber.length == indial_phone_number_lenght

Then you could check if the prefix of the number is in the your array of possible indian phone number prefixes

The following works for me:

function isValidNumber(telephoneNumber){
    var validator = /(\d{3})-*(\d{8})/;
    var results = telephoneNumber.search(validator) > -1 ? true: false;

    return results;
}

As shown here

Try using this.May be this is what you want.

 function validatePhone(phone) { //var re=/^(\\+91-|\\+91|0)?\\d{10}$/;//for pattern like +91-9198387083,9198387083,09198387083 var re = /^\\d{10}$/; //for exact 10 digits var re1 = /^(\\d{4}\\s)?\\d{7}$/; // for phone if you don't need space remove \\s if (re.test(phone)) { document.getElementById('phone').style.borderColor = '#80c75a'; //document.getElementById('phoneError').style.display = "none"; return true; } else if (re1.test(phone)) { document.getElementById('phone').style.borderColor = '#80c75a'; } else { document.getElementById('phone').style.borderColor = '#e35152'; return false; } } $("#phone").on("blur", function () { validatePhone($(this).val()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="phone" "/> 

for more you can visit here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM