I'm trying to validate a phone number. This doesn't seem to work though. Why doesn't this work?
<html>
<head>
<script>
function validateForm() {
var phone1 = document.forms["myForm"]["phone"].value;
var phone2 = ^(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$;
if ( phone1.value.match(phone2) ){
return true;
}else{
alert("Please enter a valid phone number");
return false;
}
}
</script>
</head>
<body>
<form name="myForm"
onsubmit="return validateForm()" method="post">
<label for="phone">Phone:</label><input name="phone" id="phone" value="" placeholder="Zip..." type="text" onsubmit="return validateForm()"/>
<button type="submit">Submit</button>
</form>
</body>
</html>
It definitely has something to do with the value comparison in the if statement, I just can't figure out how to accurately do this.
var phone2 = ^(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$;
it's a wrong syntax for regexes in JavaScript, it should be
var phone2 = /^(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/;
Also, you're getting field's value twice:
var phone1 = document.forms["myForm"]["phone"].value;
// ^
...
if (phone1.value.match(phone2)) {
// ^ `value` property here is not defined
See this jsfiddle with fixed code.
Your pattern RegExp , base on your pattern validation phone number is following way you should validate.
View LIVE
JS
function validateForm() {
var re = /^(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/;
var phone1 = document.forms["myForm"]["phone"].value;
var m = re.exec(phone1);
if (m && m[0]){
return true;
}else{
alert("Please enter a valid phone number");
return false;
}
}
HTML
<form name="myForm" onsubmit="return validateForm()" method="post">
<label for="phone">Phone:</label>
<input name="phone" id="phone" value="" placeholder="Zip..." type="text" onsubmit="return validateForm()" />
<button type="submit">Submit</button>
</form>
Use should use RegExp Pattern
^((\+?)(1?(\-?)?))(\d{3})(-|\s)?\d{3}(-|\s)?\d{4}$
Users tend to enter details in a textbox the way they like. It is an annoying experience if the form resticts them from entering the details in a specific fashion in a textbox. Its better to generalize your regex for such patterns. @sainaen has pointed out the errors already but your regex can still fail in the following cases.
+1-234-123-1234
+1234-123-1234
+1234123-1234
+12341231234
2341231234
434-123-1234 //with a space in the end or beginning
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.