简体   繁体   English

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

[英]Trigger jQuery form validation only if form has already been submitted?

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();
});

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 . 但问题是, 即使用户尚未提交表单一次 ,这将始终导致lstPersonId被验证并在无效时显示错误。 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? 是否有一些值我可以查看用户是否已尝试提交表单,或者其他方式我可以实现此行为?

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');
});

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');

Have you tried using using the submit event handler? 您是否尝试过使用submit事件处理程序?

$("form").submit(function() {
    //validate here
});

source: http://api.jquery.com/submit/ 来源: http //api.jquery.com/submit/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM