Might be a simple question, but I can't find an answer that fits this bit of code :(
I need to validate a phone number to have EXACTLY 11 digits (no letters)
function validateForm3() {
var x=document.forms["booking"]["number"].value;
if (x==null || x=="")
{
alert("Please fill in 11 numbers");
return false;
}
var x=document.forms["booking"]["email"].value;
if (x.indexOf("@")=== -1)
{
alert("Please enter a valid email");
return false;
}
}
I can't really change the structure of this, so it needs to fit into this bit of code :( any suggestions or answers is greatly appeciated :)
Use regexp.test
:
if (! /^[0-9]{11}$/.test(x)) {
alert("Please input exactly 11 numbers!");
return false;
}
Note that you're intentionally excluding a lot of phone numbers, including international ones or alternative writing styles of phone numbers you could reach. You should really just test for /^\+?[0-9]+$/
.
if (!/^\d{11}$/.test(x))
alert('These are not 11 digits!');
else
alert('Passed!');
Try it http://jsfiddle.net/LKAPN/1/
Use regex:
"1234".match(/^\d{4}$/);
Explanation:
^ - matches the beginning of the string
\d - matches one digit
{4} - tells that we want four digits (you want thirteen then)
$ - matches the end of the string
See https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions for further reading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With