Trigger jQuery form validation only if form has already been submitted?

▼魔方 西西 提交于 2019-12-23 10:09:25

问题


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. 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?


回答1:


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



回答2:


Have you tried using using the submit event handler?

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

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



来源:https://stackoverflow.com/questions/16734177/trigger-jquery-form-validation-only-if-form-has-already-been-submitted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!