如何使用javascript验证表单和发布数据

时间:2015-10-14 13:54:01

标签: javascript jquery

我有一个验证某些输入字段的函数。到目前为止一切顺利,现在我想检查一下这个功能是否真的"是真的"如果是,则可以发布数据。

到目前为止,我有这个:

<div class="input">
    <input type="text" id="name" name="name" value="some value" />
    <div class="formerror__icon"><span class="hidden">Enter name</span></div>
</div>
<div class="input">
   <input type="email" id="email" name="email" value="some value" />
   <div class="formerror__icon"><span class="hidden">Enter email</span></div>
</div>
<div class="input">
   <input type="text" id="tel" name="tel" value="some value" />
   <div class="formerror__icon"><span class="hidden">enter phonenr</span></div>
</div>
<div class="input">
   <input type="button" class="submitContactBtn" />
</div>

我的JS看起来像这样:

function validateForm() {
  var nameReg = /\w+\s+\w+/;
  var numberReg = /^[0-9]+$/;
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

  var name = $('#name').val();
  var email = $('#customeremail').val();
  var phonenumber = $('#customertel').val();

  if (name == "") {
    $('#name').addClass('form__input--error');
    $('#name').next('.formerror__icon').show();
  }
  else if (!nameReg.test(name)) {
    $('#name').addClass('form__input--error');
    $('#name').next('.formerror__icon').show();
  }

  if (email == "") {
    $('#mail').addClass('form__input--error')
    $('#email').next('.formerror__icon').show();
  }
  else if (!emailReg.test(email)) {
    $('#email').addClass('form__input--error');
    $('#email').next('.formerror__icon').show();
  }

  if (phonenumber == "" || phonenumber.length > 8 || phonenumber.length < 8) {
    $('#customertel').addClass('form__input--error');
    $('#customertel').next('.formerror__icon').show();
  }
  else if (!numberReg.test(phonenumber)) {
    $('#tel').addClass('form__input--error');
    $('#tel').next('.formerror__icon').show();
  }
}

$('.submitContactBtn').on('click', function (e) {
  validateForm();

  // if validateForm is "true" the data must be sent - otherise re-validate!

上面的代码到目前为止工作正常,只是它试图发布无论什么,我想使函数true或false。我怎样才能做到这一点?还是有另一种方式?

4 个答案:

答案 0 :(得分:1)

您可以在验证功能中返回true,或在其他情况下false返回:{/ p>

function validateForm() {

  var nameReg = /\w+\s+\w+/;
  var numberReg = /^[0-9]+$/;
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

  var name = $('#name').val();
  var email = $('#customeremail').val();
  var phonenumber = $('#customertel').val();

  if (name == "") {
    $('#name').addClass('form__input--error');
    $('#name').next('.formerror__icon').show();
    return false;
  } else if (!nameReg.test(name)) {
    $('#name').addClass('form__input--error');
    $('#name').next('.formerror__icon').show();
    return false;
  }

  if (email == "") {
    $('#mail').addClass('form__input--error')
    $('#email').next('.formerror__icon').show();
    isValid = false;
  } else if (!emailReg.test(email)) {
    $('#email').addClass('form__input--error');
    $('#email').next('.formerror__icon').show();
    return false;
  }

  if (phonenumber == "" || phonenumber.length > 8 || phonenumber.length < 8) {
    $('#customertel').addClass('form__input--error');
    $('#customertel').next('.formerror__icon').show();
    return false;
  } else if (!numberReg.test(phonenumber)) {
    $('#tel').addClass('form__input--error');
    $('#tel').next('.formerror__icon').show();
    return false;
  }

  return true;
}
//and on submit
$('.submitContactBtn').on('click', function (e) {
    if(!validateForm()) e.preventDefault();

答案 1 :(得分:1)

您重新发明轮子,使用http://jqueryvalidation.org/,您只需在type字段上设置requiredinput,即:

小例子:

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>Please provide your name, email address (won't be published) and a comment</legend>
    <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" minlength="2" type="text" required>
    </p>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" required>
    </p>
    <p>
      <label for="curl">URL (optional)</label>
      <input id="curl" type="url" name="url">
    </p>
    <p>
      <label for="ccomment">Your comment (required)</label>
      <textarea id="ccomment" name="comment" required></textarea>
    </p>
    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form>
<script>
$("#commentForm").validate();
</script>

请阅读documentation以获取高级用法。

答案 2 :(得分:1)

如果您只是这些表单,那么可以说你的想法是可以接受的,但是如果它会变大,你应该使用jquery插件,它会处理更多的情况并且更容易维护。

你可以看到小提琴here

您的简化js看起来像(有很多方法可以做到这一点,但我保留了您的主要代码):

function validateForm() {

    var nameReg = /\w+\s+\w+/;
    var numberReg = /^[0-9]+$/;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    var name = $('#name').val();
    var email = $('#customeremail').val();
    var phonenumber = $('#customertel').val();

    var errorClass = 'form__input--error';

    // assume that the form is valid by default
    var isValid = true;

    // clear all extra data added to fields after validation
    $('#name, #email, #customertel').removeClass(errorClass);

    if (!name.length || !nameReg.test(name)) {
       $('#name').addClass(errorClass);
       isValid = false;
    }

    if (!email.length || !emailReg.test(email)) {
       $('#email').addClass(errorClass);
       isValid = false;
    }

   if (phonenumber.length != 8 || !numberReg.test(phonenumber)) {
      $('#customertel').addClass(errorClass);
      isValid = false;
   }

   return isValid;

}

$('.submitContactBtn').on('click', function (e) {
    if (validateForm()) {
        // the form is valid - handle it here
    }

    // else is needed only if you want to handle something special if the form is not valid
    // unless the validation will be called again next time clicking the submitContactBtn
});

有一些额外的评论可以帮助你。 我添加了一些关于css的东西:

.formerror__icon {
    display: none;
}

.form__input--error + .formerror__icon {
    display: block;
}

直接从css显示错误消息,以使js更清晰,更易于处理。

PS:我不是很擅长正则表达式,但我确信长度(不是空的,8对于手机等等)也可以在表达式中处理

答案 3 :(得分:0)

在HTML中使用onclick

<input type="button" class="submitContactBtn" onclick="return validateForm();" />

删除js中的on事件,让validateForm();返回true或false,如下所示:

function validateForm() {

     var nameReg = /\w+\s+\w+/;
     var numberReg = /^[0-9]+$/;
     var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
     var ok = true;

    var name = $('#name').val();
    var email = $('#customeremail').val();
    var phonenumber = $('#customertel').val();

    if (name == "") {
      ok = false;
       $('#name').addClass('form__input--error');
       $('#name').next('.formerror__icon').show();
    }
    else if (!nameReg.test(name)) {
      ok = false;
       $('#name').addClass('form__input--error');
       $('#name').next('.formerror__icon').show();
    }

    if (email == "") {
      ok = false;
       $('#mail').addClass('form__input--error')
       $('#email').next('.formerror__icon').show();
    }
    else if (!emailReg.test(email)) {
      ok = false;
       $('#email').addClass('form__input--error');
       $('#email').next('.formerror__icon').show();
    }

   if (phonenumber == "" || phonenumber.length > 8 || phonenumber.length < 8) {
      ok = false;
      $('#customertel').addClass('form__input--error');
      $('#customertel').next('.formerror__icon').show();
   }
   else if (!numberReg.test(phonenumber)) {
      ok = false;
      $('#tel').addClass('form__input--error');
      $('#tel').next('.formerror__icon').show();
    }

return ok;


}