Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 757
Jez Avatar asked May 24 '13 11:05

Jez


2 Answers

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');
like image 66
Sudhanshu Yadav Avatar answered Sep 30 '22 04:09

Sudhanshu Yadav


Have you tried using using the submit event handler?

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

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

like image 22
Jude Duran Avatar answered Sep 30 '22 02:09

Jude Duran