我想驗證以下格式的電話號碼:(xxx)xxx-xxxx。 爲此,我使用了正則表達式,但它不驗證當我輸入不正確的格式,並點擊提交它不顯示任何錯誤。任何人都可以幫助我找出問題嗎?Javascript:使用正則表達式驗證號碼時出錯
代碼:
<!DOCTYPE html>
<html>
<head>
\t <title>NumerValidation</title>
</head>
<body>
\t \t <form name="myform" id="myform" action="" onsubmit="return validateForm()" method="post">
\t \t \t <table cellspacing="2" cellpadding="2" border="0">
\t \t \t <tr>
\t \t \t \t <td align="right">Telephone number</td>
\t \t \t \t <td><input type="text" name="phone" size="28" placeholder="(555) 555-5555"/></td>
\t \t \t </tr>
\t \t \t <tr>
\t \t \t \t <td align="right"></td>
\t \t \t \t <td><input type="submit" value="Submit" /> </td>
\t \t \t </tr>
\t \t </table>
\t \t </form>
\t \t <script>
\t \t \t function validateForm() {
\t \t \t var phone = document.myform.phone; \t
\t \t \t var regPhone = /^\(?[(]?[0-9]{3}[)]?[-\s]?[0-9]{3}[-]?[0-9]{4}$/im;
\t \t \t //var phone = /^\(?([0-9]{3})\)?[-]?([0-9]{3})[-]?([0-9]{4})$/;
\t \t \t if(phone.value.match(regPhone))
\t \t \t {
\t \t \t \t return true;
\t \t \t }
\t \t \t else
\t \t \t {
\t \t \t \t window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
\t \t \t \t return false;
\t \t \t }
\t \t }
\t \t </script>
</body>
</html>
無法重現。你用什麼輸入來測試? – ASDFGerte
我用1234567890. – Riya
這是因爲你的正則表達式不需要任何大括號或空格或類似的東西,因爲它們總是跟着'?'。換句話說,'/^\(?[(]?[0-9] {3} [)]?[ - \ s]?[0-9] {3} [ - ]?[0-9] { 4} $/im.test(「123456890」)=== true'。 – ASDFGerte