-2

以下表单使用 JavaScript 进行验证,但它不起作用。它仍然采取行动,而不是显示错误。我无法弄清楚代码有什么问题。看起来不错。谁能告诉我我的错误?

    <script type='text/javascript'>

function formValidator(){

    var name = document.getElementById('name');
    var alpha = /^[a-zA-Z]+$/;

    if(!alpha.test.(name.value)){
        alert('Please provide a valid name');
        name.focus;
        return false;

    }

    var email = document.getElementById('email');
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if (!filter.test(email.value)) {
    alert('Please provide a valid email address');
    email.focus;
    return false;
 }
}
</script>

<div id="contact_form">
                     <p>Stay Connected.</p>
                            </div>
  <form name="contact" method="post" action="sendmail.php" onsubmit='return formValidator();'>
    <fieldset>
      <label for="name" id="name_label">Your name *</label>
      <input type="text" name="name" id="name" size="50" value="" class="text-input" required  />


      <label for="email" id="email_label">Your email address *</label>
     <input type="text" name="email" id="email" />



        <br />
      <input type="submit" name="submit" class="button btn btn-primary btn-info" id="submit_btn" value="Send" onclick='Javascript:formValidator();'/>
    </fieldset>
  </form>

 I dont want to use only html5 validation.
4

3 回答 3

0

我猜 if 语句永远不会为真,所以永远不会返回 false。

于 2013-07-18T12:21:05.600 回答
0

替换if (!filter.test.(name.value)) {

  if (!filter.test(name.value)) {
于 2013-07-18T12:23:32.010 回答
0

这是控制台中的错误

SyntaxError: missing name after . operator
[Break On This Error]   

if(!alpha.test.(name.value)){

所以用

if (!filter.test(name.value))  instead of if(!alpha.test.(name.value)){

消除.

于 2013-07-18T12:23:33.510 回答