Javascript:使用正则表达式验证数字时出错

时间:2017-10-21 23:40:15

标签: javascript

我正在尝试以这种格式验证电话号码:(xxx)xxx-xxxx。 为此,我使用了正则表达式,但是当我输入错误的格式并点击提交时它没有显示任何错误。任何人都可以帮我识别问题吗?

代码:



<!DOCTYPE html>
<html>
<head>
	<title>NumerValidation</title>
</head>
<body>
		<form name="myform" id="myform" action="" onsubmit="return validateForm()" method="post">
			<table cellspacing="2" cellpadding="2" border="0">
			<tr>
				<td align="right">Telephone number</td>
				<td><input type="text" name="phone" size="28" placeholder="(555) 555-5555"/></td>
			</tr>
			<tr>
				<td align="right"></td>
				<td><input type="submit" value="Submit" /> </td>
			</tr>
		</table>
		</form>

		<script>

			function validateForm() {

			var phone = document.myform.phone;	
			var regPhone = /^\(?[(]?[0-9]{3}[)]?[-\s]?[0-9]{3}[-]?[0-9]{4}$/im;

		 	//var phone = /^\(?([0-9]{3})\)?[-]?([0-9]{3})[-]?([0-9]{4})$/;  
		 	if(phone.value.match(regPhone)) 
		 	{  
		 		return true;  
		 	}  
		 	else  
		 	{  
		 		window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");  
		 		return false;  
		 	} 
		 } 
		</script>

</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

使用此正则表达式

(111)111 - 1111 (111) 111 - 1111 (111) 111- 1111 (111) 111- 1111 (111) 111-1111 (111) 111 - 1111

匹配

value = value.trimLeft();
value = value.trimRight();

如果用户在电话号码的开头或结尾添加空格,则必须使用

进行修剪
$(document).ready(function() { 
    // your code here
});

如果您不在输入的开头和结尾修剪空格,即使用户输入有效数字,正则表达式也会失败