仅在表单已提交时才触发jQuery表单验证?

问题描述:

不引人注意的验证基于以下想法:在用户提交表单之前,您进行表单验证;一旦发生这种情况,如果表单上的某些内容无效,那么一旦用户更改了每个字段,就会立即对其进行验证。

Unobtrusive validation is based on the idea that you don't do form validation until the form has been submitted by the user; once that's happened, if something is invalid on the form, then each field is immediately validated once the user has changed it.

我想要做的是触发验证表单元素不引人注目 - 即,如果用户已经尝试提交表单,验证表单元素。所以我可以触发元素的验证(我在更改某个复选框时执行此操作),如下所示:

What I want to do is trigger validation on a form element "unobtrusively" - that is, only validate the form element if the user has already tried to submit the form. So I can trigger the validation of an element (I do it when a certain checkbox is changed) like so:

$('#chkNoPersonId').change(function(){
    $('#lstPersonId').valid();
});

但问题是总是导致 lstPersonId 要验证并在无效时显示错误,即使用户尚未提交表单。我希望只有在用户尝试提交表单后才能对其进行验证。是否有一些价值我可以查看用户是否已尝试提交表单,或者其他方式我可以实现此行为?

But the trouble is that that will always cause lstPersonId to be validated and an error displayed when invalid, even if the user hasn't yet submitted the form once. I want it to only be validated once the user has tried to submit the form. Is there some value I can check to see whether the user has tried to submit the form yet, or some other way I can achieve this behaviour?

您可以在提交按钮上添加一个标志,以识别表单提交是否已被点击。
ex:

You can add a flag on submit button to identify form submit has been already clicked or not. ex:

$('#submitButn').click(function(){
   $(this).attr('data-submitted','true');
});

在输入检查天气的每次验证中,该标志是否为真,并执行验证逻辑。 / p>

Than in each validation of input check weather that flag is true or not and perform your validation logic.

$('#chkNoPersonId').change(function(){
  if( $('#submitButn').attr('data-submitted')=='true'){
   $('#lstPersonId').valid();
  }
});

在清除或重置表格后,您可以删除该属性

On clear or reset of form you can remove that attribute

 $('#submitButn').removeAttr('data-submitted');