istavros
istavros

Reputation: 158

jquery validation multiple error label locations

Using jquery validation, is there a way to have each error message displayed in a different location.

I want to display the "required" message next to the email field, but the "invalid email address" in a validation summary div at the bottom of the form.

I know i can use errorPlacement but I think this is for all messages.

Upvotes: 1

Views: 769

Answers (1)

Adam Botley
Adam Botley

Reputation: 702

Use the errorPlacement method in .validate() to contain the error placement logic. 2 arguements are passed to errorPlacement:

  1. error: the error text to be inserted into the DOM.
  2. element: the element being validated.

You can use the error message returned by the validator to decide where it should be positioned. EG:

$("form").validate({
  ignore: '',
  errorPlacement: function(error, element){
    if(error.text() == "This field is required"){
      $('.requiredContainer').text(error.text());
    }
    else
    {
      $('.genericContainer').text(error.text());
    }
  });
});

If you're using this with multiple forms, I would suggest putting all of your validator settings in setDefaults() and just using validate() to handle rules/messages etc

setDefaults docs

Upvotes: 1

Related Questions