Xroad
Xroad

Reputation: 425

jQuery Validate plugin - Handling of error messages

Can I have some help for my form please

I use the validate plugin.

http://jsfiddle.net/Xroad/2pLS2/23/

I would like a single general message for all empty fields and once the field is filled with a custom field below the concerned message (like "Please enter at least 2 characters")

How can I do that please ?

$.validator.setDefaults({
    errorClass: 'error-image',
    validClass: 'ok-image',
    errorElement: 'span',
    errorContainer: '#invalid-empty',
    errorPlacement: function(error,element) {
    return true;
  }
});

$("#form-general").validate({

    rules: {
        firstname: {
            minlength: 2,
            maxlength: 25
        },
        name: {
            minlength: 2,
            maxlength: 25
        },
        email: {
            email: true
        }
    }

});

Upvotes: 1

Views: 1369

Answers (2)

ryanwinchester
ryanwinchester

Reputation: 12127

You can use the messages option to specify custom messages.

Check this JSFiddle for a demo.

Adding custom messages to the options and remove empty errorPlacement:

$.validator.setDefaults({
  errorClass: 'error-image',
  validClass: 'ok-image',
  errorElement: 'span',
  errorContainer: '#invalid-empty',
  //errorPlacement: function(error,element) {
  //  return true;
  //},
  messages: {
    name: {
      required: "",
      minlength: "Dude, your first name is longer than that..."
    },
    firstname: {
      required: "",
      minlength: "I know you can type at least one more character!"
    },
    email: {
      required: "",
      email: "Your email address must be in the format of [email protected]"
    },
    telephone: "",
    message: ""
  }
});

Just specify whatever rule you want to over-ride the default message for, and write your custom message.

Since you only want your general required message at the top, you can just overwrite required messages as empty strings so that nothing shows up below the input.

Upvotes: 2

Ryley
Ryley

Reputation: 21216

Just remove your errorPlacement option and it will do that automatically. By having this:

errorPlacement: function(error,element) {
    return true;
}

You are telling jQuery Validate to not place error messages at all. Removing it will allow the plugin to place the messages, which sounds like what you want. If you want to skip required messages but allow the other messages, you might have to get fancy with the error part of errorPlacement. It contains the message string, so it will say something about "required", which you could RegExp for and not display.

Perhaps:

errorPlacement: function(error,element) {
    if (/required/.test(error.text()){
        return false;
    } else {
        error.insertAfter(element);
    }
}

Upvotes: 0

Related Questions