使用jquery验证表单输入字段

时间:2018-05-31 11:12:38

标签: javascript jquery html forms validation

  1. 我正在进行表单验证。一切都工作正常,我真正想要的是我想添加一些更多的输入字段,如复选框,单选按钮,选择和textarea,上传文件等,所以我希望它们也被验证。

  2. 我收到了电子邮件输入错误,但它无法正常工作,因为它应首先验证电子邮件然后它应该删除错误消息,但它只是在输入几个字符后删除错误消息。

  3. 我希望验证电话号码。就像用户应该在印度输入10位数字一样,如果在另一个国家/地区会有所不同,我会对如何做到这一点感到困惑。

  4. 我希望在正确验证所有字段时弹出成功消息。我试过的是这个:

    $('.success_msg').fadeIn().delay(3000).fadeOut();
    $('input , textarea , select').val('').removeClass('valid');
    event.preventDefault();
    
  5. 我希望在完成所有验证并发送成功消息后清除所有字段。

  6. 有人能指出我正确的方向吗?

    
    
    var Validator = function(formObject) {
      this.form = $(formObject);
    
      var Elements = {
        name: {
          reg: /^[a-zA-Z]{2,20}$/,
          error: "Not a valid name.",
        },
    
        email: {
          reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
          error: "Not a valid e-mail address.",
        },
        phone: {
          reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
          error: "Not a valid number.",
        },
    
        message: {
          reg: /^(?!\s*$).+/,
          error: "Message field cannot be empty.",
        },
      };
    
      var handleError = function(element, message) {
        element.addClass('input-error');
        var $err_msg = element.parent('div');
        $err_msg.find('.error').remove();
        var error = $('<div class="error"></div>').text(message);
        error.appendTo($err_msg);
        element.keyup(function() {
          $(error).fadeOut(1000, function() {
            element.removeClass('input-error');
          });
        });
    
      };
    
      this.validate = function() {
        var errorCount = 0;
        this.form.find("input, textarea").each(function(index, field) {
          var type = $(field).data("validation");
          var validation = Elements[type];
          if (validation) {
            if (!validation.reg.test($(field).val())) {
              errorCount++;
              handleError($(field), validation.error);
            }
          }
        })
        return errorCount == 0;
      };
    };
    
    $(function() {
      $("form#test").on("submit", function(event) {
        //event.preventDefault();
        return new Validator(this).validate(); // "this" here refers to the form
    
      })
    })
    &#13;
    body {
      background: #fff;
      color: #333;
      font: 76% Verdana, sans-serif;
    }
    
    form {
      margin: 1em 0 0 2em;
      width: 90%;
    }
    
    fieldset {
      margin: 0;
      border: 1px solid #ccc;
      padding-bottom: 1em;
    }
    
    legend {
      font-weight: bold;
      text-transform: uppercase;
    }
    
    label {
      float: left;
      width: 5em;
      padding-right: 2em;
      font-weight: bold;
    }
    
    div {
      margin-bottom: 30px;
    }
    
    input {
      font: 1em Verdana, sans-serif;
    }
    
    fieldset ul li input {
      float: left;
      width: 120px;
      border: 1px solid #ccc;
    }
    
    textarea {
      width: 300px;
      height: 200px;
      border: 1px solid #ccc;
      font: 1em Verdana, sans-serif;
    }
    
    form p {
      margin: 0;
      padding: 0.4em 0 0 7em;
    }
    
    form p input {
      background: #666;
      color: #fff;
      font-weight: bold;
    }
    
    div.error {
      clear: left;
      margin-left: 5.3em;
      color: red;
      padding-right: 1.3em;
      height: 100%;
      padding-bottom: 0.3em;
      line-height: 1.3;
    }
    
    .input-error {
      background: #ff9;
      border: 1px solid red;
    }
    
    .success_msg {
      width: 350px;
      line-height: 40px;
      border: 1px solid green;
      border-radius: 5px;
      background-color: rgba(213, 255, 187, 0.7);
      display: none;
      position: absolute;
      bottom: 5px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 999;
      text-align: center;
    }
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action="#" method="post" id="test">
    
      <fieldset>
    
        <legend>Contact information</legend>
    
    
        <div>
          <label for="firstname">Firstname:</label>
          <input type="text" name="firstname" id="firstname" data-validation="name" />
        </div>
    
    
        <div>
          <label for="lastname">Lastname:</label>
          <input type="text" name="lastname" id="lastname" data-validation="name" />
        </div>
    
        <div>
          <label for="email">Email:</label>
          <input type="email" name="email" id="email" data-validation="email" />
    
        </div>
        <div>
          <label for="phone">phone</label>
          <input type="number" name="phone" id="phone" data-validation="phone" />
        </div>
    
        <div>
          <label>Gender:</label>
          <input type="radio" name="gender" value="male" data-validation="gender" />
          <input type="radio" name="gender" value="female" data-validation="gender">
        </div>
    
        <div>
          <label>select</label>
          <input type="checkbox" name="checkbox" id="checkbox1" value="demo1" data-validation="checkbox" />
          <input type="checkbox" name="checkbox" id="checkbox2" value="demo2" data-validation="checkbox" />
          <input type="checkbox" name="checkbox" id="checkbox3" value="demo3" ata-validation="checkbox" />
        </div>
    
        <select data-validation="selectOption">
          <option value="">Select any option</option>
          <option value="red">Red</option>
          <option value="blue">Blue</option>
          <option value="green">Green</option>
        </select>
    
        <div>
          <label>Upload:</label>
          <input type="file" name="file" id="file" data-validation="file" />
        </div>
    
        <div>
          <label for="message">Message:</label>
          <textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
        </div>
    
        <p><input type="submit" name="send" id="send" value="Send" /></p>
    
      </fieldset>
      <div class="success_msg">
        <p>Form submitted Successfully</p>
      </div>
    </form>
    &#13;
    &#13;
    &#13;

    在投入时间回答问题之前,请随时清除疑虑。

2 个答案:

答案 0 :(得分:11)

以下是工作代码:

https://jsfiddle.net/bhumi/o2gxgz9r/47570/

我已将选择器更改为使用ID

您需要在句柄错误中使用循环:

var Validator = function(form) {

    this.form = $(form);

    var Elements = {
        name: {
            selector: $('input[type=text]'),
            reg: /^[a-zA-Z]{2,20}$/
        },

        email: {
            selector: $('input[type=email]'),
            reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i
        },

        message: {
            selector: $('textarea'),
            reg: /^\s+$/
        }
    };

    var handleError = function(element, message, v1) {
        if (v1.selector.length > 1) {
            var ss = v1.selector;

            $(ss).each(function(i, v) {
            $(v).removeClass('input-error');
            if($(v).val() == ''){
              $(v).addClass('input-error');
              var $err_msg = $(v).parent('div');
              if($(v).parent('div').find('.error').length == 0) {
                    var error = $('<div class="error"></div>').text(message);
               }else{
                    $(v).parent('div').find('.error').text('');
                    var error = $(v).parent('div').find('.error').text(message);
                    $(this).siblings('.error').show();
               }
               error.appendTo($err_msg);
             }else{
               $(v).siblings('.error').text('')
             }
             $(v).keyup(function() {
                 $(error).fadeOut(1000, function() {
                     element.removeClass('input-error');
                });
             });
          });
        } else {
            element.addClass('input-error');
            var $err_msg = element.parent('div');
            if(element.parent('div').find('.error').length == 0) {
                  var error = $('<div class="error"></div>').text(message);
             }else{
                  element.parent('div').find('.error').text('');
                  var error = element.parent('div').find('.error').text(message);
                  $(this).siblings('.error').show();
             }
            error.appendTo($err_msg);
            element.keyup(function() {
                $(error).fadeOut(1000, function() {
                    element.removeClass('input-error');
                });
            });
        }

    };

    this.validate = function() {

        this.form.submit(function(e) {

            for (var i in Elements) {

                var type = i;
                var validation = Elements[i];
                switch (type) {
                    case 'name':
                        if (!validation.reg.test(validation.selector.val())) {
                            handleError(validation.selector, 'Not a valid name.', validation);
                        }
                        break;
                    case 'email':
                        if (!validation.reg.test(validation.selector.val())) {
                            handleError(validation.selector, 'Not a valid e-mail address.', validation);
                        }
                        break;
                    case 'message':
                        if (validation.reg.test(validation.selector.val()) || validation.selector.val() == '') {
                        handleError(validation.selector, 'Message field cannot be empty.', validation);
                        }
                        break;
                    default:
                        break;


                }

            }

            e.preventDefault();
        });

    };
};

var validator = new Validator('#test');
validator.validate();

答案 1 :(得分:1)

我希望这是你想要实现的目标。这花费的时间比预期的要长,但我试图实现它。整个表格是自定义表格。您可以使用现有的插件来实现它。任何方式需要花费很多时间来弄明白。考虑一下这个问题,因为大多数事情都在起作用,如果某些事情不符合您的要求,请忽略它。

&#13;
&#13;
$(document).ready(function() {

  /* contact form validation */
  var Validator = function(formObject) {
    this.form = $(formObject);
    var Elements = {
      name: {
        reg: /^[a-zA-Z ]{2,20}$/,
        require: true,
        error: "Not a valid name.",
      },

      email: {
        reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
        error: "Not a valid e-mail address.",
      },
      phone: {
        reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
        error: "Not a valid number.",
      },

      message: {
        reg: /^(?!\s*$).+/,
        error: "Message field cannot be empty.",
      },
      gender: {
        error: "gender is required",
      },
      selectOption: {
        error: "this field is required",
        required: true
      }
    };

    var handleError = function(element, message) {
      element.addClass('input-error');
      var $err_msg = element.parent('div');
      $err_msg.find('.error').remove();

      var error = $('<div class="error"></div>').text(message);
      error.appendTo($err_msg);
      console.log(element);


      element.on('keypress change', function() {
        $(error).fadeOut(1000, function() {
          console.log(element);
          element.removeClass('input-error');
        });
      });

    };

    /* Select Option */

    this.validate = function() {
      var errorCount = 0;

      this.form.find("select").each(function(index, field) {
        var type = $(field).data("validation");
        var validation = Elements[type];
        if ($(field).val() == "") {
          errorCount++;
          handleError($(field), validation.error);
        }
      });

      this.form.find("input, textarea").each(function(index, field) {
        var type = $(field).data("validation");
        var validation = Elements[type];
        if (validation !== undefined) {
          var re = new RegExp(validation.reg);
          if (validation) {
            if (!re.test($(field).val())) {
              errorCount++;
              handleError($(field), validation.error);
            }
          }
        }
      })

      /* Radio button */

      var radioList = $('input:radio');
      var radioNameList = new Array();
      var radioUniqueNameList = new Array();
      var notCompleted = 0;
      for (var i = 0; i < radioList.length; i++) {
        radioNameList.push(radioList[i].name);
      }
      radioUniqueNameList = jQuery.unique(radioNameList);
      console.log(radioUniqueNameList);
      for (var i = 0; i < radioUniqueNameList.length; i++) {
        var field = $('#' + radioUniqueNameList[i]);
        var type = field.data("validation");
        var validation = Elements[type];
        if ($('input[name=' + type + ']:checked', '#test').val() == undefined) {
          errorCount++;
          handleError($(field), validation.error);
        }
      }

      return errorCount == 0;
    };
  };

  /* Submit form*/

  $(function() {

    $("form#test").on('submit', function(e) {
      var NoErrors = new Validator(this).validate();
      if (NoErrors == true) {
        $.ajax({
          url: this.action,
          type: this.method,
          data: $(this).serialize(),
          success: function() {
            // AJAX request finished, handle the results and error msg
            $('.success_msg').fadeIn().delay(3000).fadeOut();
            $('input[type!="submit"], textarea').val('').removeClass('error');
          }
        });

      }
      return false;
    })

  })

});
&#13;
body {
  background: #fff;
  color: #333;
  font: 76% Verdana, sans-serif;
}

form {
  margin: 1em 0 0 2em;
  width: 90%;
}

fieldset {
  margin: 0;
  border: 1px solid #ccc;
  padding-bottom: 1em;
}

legend {
  font-weight: bold;
  text-transform: uppercase;
}

label {
  float: left;
  width: 5em;
  padding-right: 2em;
  font-weight: bold;
}

div {
  margin-bottom: 30px;
}

input {
  font: 1em Verdana, sans-serif;
}

fieldset ul li input {
  float: left;
  width: 120px;
  border: 1px solid #ccc;
}

textarea {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  font: 1em Verdana, sans-serif;
}

form p {
  margin: 0;
  padding: 0.4em 0 0 7em;
}

form p input {
  background: #666;
  color: #fff;
  font-weight: bold;
}

div.error {
  clear: left;
  margin-left: 5.3em;
  color: red;
  padding-right: 1.3em;
  height: 100%;
  padding-bottom: 0.3em;
  line-height: 1.3;
}

.input-error {
  background: #ff9;
  border: 1px solid red;
}

.success_msg {
  width: 350px;
  line-height: 40px;
  border: 1px solid green;
  border-radius: 5px;
  background-color: rgba(213, 255, 187, 0.7);
  display: none;
  position: absolute;
  bottom: 5px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
  text-align: center;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="#" method="post" id="test">
  <fieldset>

    <legend>Contact information</legend>


    <div>
      <label for="firstname">Firstname:</label>
      <input type="text" name="firstname" id="firstname" data-validation="name" />
    </div>


    <div>
      <label for="lastname">Lastname:</label>
      <input type="text" name="lastname" id="lastname" data-validation="name" />
    </div>

    <div>
      <label for="email">Email:</label>
      <input type="email" name="email" id="email" data-validation="email" />

    </div>
    <div>
      <label for="phone">phone</label>
      <input type="number" name="phone" id="phone" data-validation="phone" />
    </div>

    <div>
      <label>Gender:</label>
      <input type="radio" name="gender" value="male" data-validation="gender" />
      <input type="radio" name="gender" value="female" data-validation="gender">
    </div>

    <select data-validation="selectOption">
      <option value="">Select any option</option>
      <option value="red">Red</option>
      <option value="blue">Blue</option>
      <option value="green">Green</option>
    </select>

    <div>
      <label for="message">Message:</label>
      <textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
    </div>

    <p><input type="submit" name="send" id="send" value="Send" /></p>

  </fieldset>
  <div class="success_msg">
    <p>Form submitted Successfully</p>
  </div>
</form>
&#13;
&#13;
&#13;