如何在提交时使用 jquery 验证来验证表单?

How to validate form using jquery validation on submit?

我正在尝试使用 jQuery 验证 js 来验证我的表单,但问题是我在 toastr 中没有收到任何错误消息。

我按照这个 link 来实现 toastr 中的错误。我收到的错误是文本框下方的 'This field is required'。下面是我的代码:

HTML

<form class="card-body">
  <div class="form-row">
    <div class="col-md-6 mb-3">
      <label for="validationDefault01">First name</label>
      <input type="text" class="form-control" id="validationDefault01" name="firstName">
    </div>
    <div class="col-md-6 mb-3">
      <label for="validationDefault02">Last name</label>
      <input type="text" class="form-control" id="validationDefault02" name="lastName">
    </div>
  </div>
  <div class="form-row">
    <div class="col-md-6 mb-3">
      <label for="validationDefault03">City</label>
      <input type="text" class="form-control" id="validationDefault03" name="city">
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationDefault04">State</label>
      <select class="custom-select" id="validationDefault04" name="state">
        <option selected disabled value="">Choose...</option>
        <option>...</option>
      </select>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationDefault05">Zip</label>
      <input type="text" class="form-control" id="validationDefault05" name="zip">
    </div>
  </div>
  <div class="row">
    <div class="col-md-3 mb-3">
      <label for="username">Username</label>
      <input type="text" class="form-control" id="username" name="username">
    </div>
    <div class="col-md-3 mb-3">
      <label for="password">Password</label>
      <input type="text" class="form-control" id="password" name="password">
    </div>
  </div>
  <div class="form-group">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" id="invalidCheck2" name="confirm">
      <label class="form-check-label" for="invalidCheck2">
        Agree to terms and conditions
      </label>
    </div>
  </div>
  <button class="btn btn-success" type="submit" id="submitBtn">Submit</button>
  <button class="btn btn-danger" type="reset">Reset</button>
</form>

JS

function toasterOptions() {
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "preventDuplicates": true,
        "onclick": null,
        "showDuration": "100",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "show",
        "hideMethod": "hide"
    };
};



$(document).ready(function () {
    toasterOptions();
    $('form').submit(function(e) { 
        e.preventDefault();
        $(this).validate({
            rules: {
                firstName: 'required',
                lastName: 'required'
            },
            messages: {
                firstName: () => {
                    toastr.error('First Name required')
                },
                lastName: () => {
                    toastr.error('Last Name required')
                }
            }
        });
        var values = $(this).serializeArray();
        var xyz = {};
        $.each(values, function (i, obj) { 
            xyz[obj.name] = obj.value
        });
        window.localStorage.setItem('data', JSON.stringify(xyz));
        toastr['info']('Done');
    });
});

有什么遗漏的吗?

伙计只是将 Required 属性放入应该为您完成的输入元素中, 在填写这些必需的属性之前,发件人不会提交。

<input type="text" required class="form-control" id="validationDefault02" name="lastName">

第一个问题是,你应该在提交函数之外声明你的验证(只声明验证一次)

其次,您必须对每个条件使用消息验证作为 returns 您的烤面包机消息的功能,例如:

 "firstName": {
      required: function() {
           toastr.error('First Name required')
      },
  },

还建议为您的表单使用 ID,并通过单击按钮设置提交,并使用 jquery 验证 valid() 函数

检查表单是否有效

请参阅下面的工作片段:

function toasterOptions() {
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "preventDuplicates": true,
        "onclick": null,
        "showDuration": "100",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "show",
        "hideMethod": "hide"
    };
};



$(document).ready(function () {
    toasterOptions();
    var form = $("#my-form");
    form.validate({
        onfocusout: false,
        rules: {
            "firstName": {
              required: true,
            },
            "lastName": {
              required: true,
            }
        },
        messages: {
            "firstName": {
              required: function() {
                  toastr.error('First Name required')
              },
            },
            "lastName": {
                required: function() {
                    toastr.error('Last Name required')
                },
            },
        },
        
        submitHandler: function(form {
          var values = $(form).serializeArray();
           console.log(values);
          var xyz = {};
          $.each(values, function (i, obj) { 
              xyz[obj.name] = obj.value
          });
          //window.localStorage.setItem('data', JSON.stringify(xyz));
          toastr['info']('Done');

        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" integrity="sha512-VEd+nq25CkR676O+pLBnDW09R7VQX9Mdiij052gVCp5yVH3jGtH70Ho/UUv4mJDsEdTvqRCFZg0NKGiojGnUCw==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.css" integrity="sha512-3pIirOrwegjM6erE5gPSwkUzO+3cTjpnV9lexlNZqvupR64iZBnOOTiiLPb9M36zpMScbmUNIcHUqKD47M719g==" crossorigin="anonymous" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js" integrity="sha512-UdIMMlVx0HEynClOIFSyOrPggomfhBKJE28LKl8yR3ghkgugPnG6iLfRfHwushZl1MOPSY6TsuBDGPK2X4zYKg==" crossorigin="anonymous"></script>

<form id="my-form" class="card-body">
  <div class="form-row">
    <div class="col-md-6 mb-3">
      <label for="validationDefault01">First name</label>
      <input type="text" class="form-control" id="validationDefault01" name="firstName">
    </div>
    <div class="col-md-6 mb-3">
      <label for="validationDefault02">Last name</label>
      <input type="text" class="form-control" id="validationDefault02" name="lastName">
    </div>
  </div>
  <div class="form-row">
    <div class="col-md-6 mb-3">
      <label for="validationDefault03">City</label>
      <input type="text" class="form-control" id="validationDefault03" name="city">
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationDefault04">State</label>
      <select class="custom-select" id="validationDefault04" name="state">
        <option selected disabled value="">Choose...</option>
        <option>...</option>
      </select>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationDefault05">Zip</label>
      <input type="text" class="form-control" id="validationDefault05" name="zip">
    </div>
  </div>
  <div class="row">
    <div class="col-md-3 mb-3">
      <label for="username">Username</label>
      <input type="text" class="form-control" id="username" name="username">
    </div>
    <div class="col-md-3 mb-3">
      <label for="password">Password</label>
      <input type="text" class="form-control" id="password" name="password">
    </div>
  </div>
  <div class="form-group">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" id="invalidCheck2" name="confirm">
      <label class="form-check-label" for="invalidCheck2">
        Agree to terms and conditions
      </label>
    </div>
  </div>
  <button class="btn btn-success"  id="submitBtn" type="submit">Submit</button>
  <button class="btn btn-danger" type="reset">Reset</button>
</form>