简体   繁体   English

电话号码验证问题

[英]Phone number validation problems

I have written some javascript to validate a phone number field if something is entered (it is an optional field) but it doesn't seem to be working, if i enter wrong values it still submits. 我已经写了一些javascript来验证电话号码字段,如果输入了某些内容(它是一个可选字段),但它似乎没有工作,如果我输入了错误的值,它仍然提交。 Here is my code: 这是我的代码:

<script>
function validatePhone()
{ 
var num1 = document.getElementById('workno');

if (num1 !== null)
    {
    regex = /\(\d{2}\)\d{8}/;
    }
if (!num1.match(regex))
    {
    alert('That is not a correct telephone number format');
    return false;
    }
}
 </script>

<form name="eoiform" form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validatePhone();">

<input type="text" id="workno" name="workno">

<input type="submit" name="submit" id="submit" value="submit">

</form>

Can anyone spot my mistake? 谁能发现我的错误?

Your num1 variable contains an element object, not its value so can't be tested with a regexp as it stands. 您的num1变量包含一个元素对象,而不是其值,因此无法使用正则表达式进行测试。

It will only ever by null if the element does not exist; 如果元素不存在,它将只返回null; it will be "" if its got no value. 如果它没有价值,它将是“”。

function validatePhone()
{ 
  var num1 = document.getElementById('workno').value;
  if (num1 !== "" && !num1.match(/\(\d{2}\)\d{8}/))
  {
    alert('That is not a correct telephone number format');
    return false;
  }
}

You also have the invalid form method="POST" in your HTML. 您的HTML中也有无效的form method="POST"

Maybe you should select the value from the Input. 也许你应该从输入中选择值。 Can you try 你能试一下吗

if (!num1.value.match(regex))

In addition to the problems noted in the other answers, you should also anchor the regexp. 除了其他答案中提到的问题之外,您还应该锚定正则表达式。 Otherwise, it will allow extra characters outside the phone number. 否则,它将允许电话号码之外的额外字符。

function validatePhone()
{ 
  var num1 = document.getElementById('workno').value;
  if (num1 !== "" && !num1.match(/^\(\d{2}\)\d{8}$/))
  {
    alert('That is not a correct telephone number format');
    return false;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM