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?
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?
$("form").submit(function() {
//validate here
});
source: http://api.jquery.com/submit/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With