I have a form that collects some personal information from the end user and triggers some JS validation functions. For simplistic examples lets just say the form has first name, last name, and email address.
Now once the form is filled out and submitted, if I go back to it my browser pre-populates the form like you would expect. The problem is when I go to submit (without changing any fields or tabbing through them) the plugin does not go back and validate those fields (if they have been pre-populated.
I am not sure WHY it is not validating the pre-populated fields. And I am not sure how to get it to. Does anyone have any ideas? I am running the latest version of jQuery and the validate plugin (http://jqueryvalidation.org/).
Sample code:
$(document).ready(function() {
var rules = {
FirstName: 'required',
LastName: 'required',
EmailAddress: {
required: true,
customEmail: true,
checkAccountExists: true
}
};
//And field specific (and even validation type specific) error messages
var messages = {
FirstName: 'Your first name is required.',
LastName: 'Your last name is required.',
EmailAddress: {
required: 'Your email address is required.',
customEmail: 'You must enter a valid email address.',
checkAccountExists: 'We already have an account with that email address. Please login.'
}
};
$('#applicationForm').validate({
//debug: true,
rules: rules,
messages: messages,
errorElement: 'span'
});
});
jQuery.validator.addMethod('customEmail', function(value, element) {
return this.optional(element) || /[A-z0-9._%-+]{1,}@[A-z0-9._%-]{1,}\.[A-z0-9._%-]{1,}/.test(value);
}, 'Invalid email address entered.');
jQuery.validator.addMethod('checkAccountExists', function(value, element) {
if (this.optional(element)) {
return true;
}
var url = $(element).attr('checkEmailUrl');
$.ajax({
type: 'GET',
data: {EmailAddress: value, check: true},
dataType: 'json',
url: url,
success: function(response) {
var dataArray = jQuery.parseJSON(response);
//If it exists then trigger the popup
if (dataArray.result == 'EXISTS') {
kclHelpers.showEmailExistsModal(value);
}
}
});
return true; //If it exists the popup will handle it. We are just using this to trigger it
}, 'An account under the specified email address already exists. Please sign in.');
A simple solution that I employ is just to trigger the blur event already bound to elements you want to validate. You can check the value of each element to determine if they should be validated which prevents this operation from triggering them before the user has interacted.
$(window).load(function() {
//pre-highlight fields with values
$('input[type=text], input[type=email], input[type=url], input[type=password], select').filter(function() {
return $.trim($(this).val()) != '';
}).blur();
});
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