2

I added a jQuery validation rule, so at least one checkbox of class "require-one" has to be checked in order for the form to validate.

$(".require-one").rules("add", {
  required: true,
  minlength: 1,
  messages: {
    required: "Check at least one"
  }
});

It works great, the form does not submit and focus is set to the first checkbox.

But how do I get it to show the error message in:

<span id="require-one-errormessage></span>

Thanks in advance

2
  • Title says div but OP shows span. Commented Dec 21, 2014 at 19:19
  • Where is your .validate() method and the relevant HTML? Commented Dec 21, 2014 at 19:22

1 Answer 1

2

You can change the default label element into anything by using the errorElement option within your .validate() method.

$('#myForm').validate({
    errorElement: "span",
    // your other options
});

You could then use the errorPlacement option to place the element within your layout. Use a conditional to place for one type versus another.

$('#myForm').validate({
    errorElement: "span",
    errorPlacement: function(error, element) {
        if ($(element).is(':checkbox')) {
            error.insertBefore(element); // custom
        } else {
            error.insertAfter(element);  // default
        }
    },
    // your other options
});

AFAIK, because the error element is created and toggled dynamically by the plugin, there's no way to assign an id, nor would there be a point. However, you could assign a different class to all error messages, if needed, by using the errorClass option.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.