Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery Validation plugin with form-level server-side validation?

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.

like image 943
user126715 Avatar asked Aug 09 '11 17:08

user126715


People also ask

Does jQuery validate require a form?

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.

How we can use jQuery validation plugins in MVC?

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.

Can we do server side validation using JavaScript?

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.


1 Answers

I think I figured it out from the documentation of Validator/showErrors

var validator = $("#contact_form").validate();
validator.showErrors({"state": "Bad state."});
like image 112
user126715 Avatar answered Oct 05 '22 13:10

user126715