What's the best way to trigger errors on elements for server-side validation errors that come back after the form passes the initial client-side validation?
$("#contact_form").validate({
submitHandler: function(form) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/contact/send',
data: $(form).serialize(),
success: function(response) {
if(response.error) { //server came back with validation issues
var fields = response.fields;
for(var i=0, var len = fields.length; i < len; i++) {
var field_name = fields[i].name;
var field_error = fields[i].error;
// TRIGGER ERROR ON AFFECTED ELEMENT
}
return false;
}
//everything went ok, so let's show a thanks message
showThanks();
}
}
});
I'm thinking something like:
$(form).find("[name='" + field_name + "']").triggerError(field_error);
But I didn't see any api methods for manually triggering errors in that manner.
The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.
UnobtrusiveJavaScriptEnabled" property value back to false and create a new file in "Scripts" folder and name it "script-custom-validator. js". Add the Jquery validator code in it as shown below i.e. The above piece of code attaches my account register form with jQuery form validator by using form ID.
Validation can be defined by many different methods, and deployed in many different ways. Server side validation is performed by a web server, after input has been sent to the server. Client side validation is performed by a web browser, before input is sent to a web server.
I think I figured it out from the documentation of Validator/showErrors
var validator = $("#contact_form").validate();
validator.showErrors({"state": "Bad state."});
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