简体   繁体   中英

How to validate if the input text (in html) is a valid Phone Number when user hits the 11th number?

I have an input box. How can I simultaneously validate if the input text is a valid Phone Number, exactly when user hits the 11th number in the input?

Here's what I tried so far:

 function validPhone(phoneNum) // check for valid phone numbers in the format 999-999-9999 { var strPhone = phoneNum.value; var rePhone = /\\d{3}-\\d{3}-\\d{4}/; var blnResult = true; if (strPhone.length !== 0 && (strPhone.length !== 12 || strPhone.match(rePhone) == null)) { blnResult = false; phoneNum.select(); alert("Phone number is invalid. Please try again."); phoneNum.focus(); } return blnResult; };
 <input class="form-control" onBlur="validPhone(this)" type="text" name="username" placeholder="Enter Phone number" id="phoneNumberForForgotPassword" data-val-required="نام کاربری را وارد نمائید.">

You can use oninput to check if input has some values entered or not.

When 10th value is entered you can use a alert but this will not be enough because after alert , user can still enter more values. So use maxlength="10" to allow only 10 numbers.

Also if you don't want to allow text but numbers only than you can use .replace(/[^\\d]/, '') to replace any non-number . And show that it is not a number.

 function validPhone(phoneNum) // check for valid phone numbers in the format 999-999-9999 { if (phoneNum.value.match(/[^\\d]/)) { phoneNum.value = phoneNum.value.replace(/[^\\d]/, '') document.querySelector("#demo1").innerHTML = "Sorry numbers only"; } else { document.querySelector("#demo1").innerHTML = ""; } var strPhone = phoneNum.value; var rePhone = /\\d{3}-\\d{3}-\\d{4}/; if (strPhone.length >= 10) { phoneNum.select(); document.querySelector("#demo1").innerHTML ="No more numbers plz, only 10 digits allowed in Phone number."; } document.querySelector("#demo").innerHTML = strPhone.length; };
 #demo1 { color: red; }
 <input class="form-control" oninput="validPhone(this)" type="text" name="username" placeholder="Enter Phone number" maxlength="10" id="phoneNumberForForgotPassword" data-val-required="نام کاربری را وارد نمائید."> <div id="demo1"></div> <div id="demo"></div>

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