0

I'm using Jquery Validate to validate a form. I've added a custom validation method via

$.validator.addMethod

If I add this method to a textbox, the validation will work without problems.

I want this custom validation method to highlight a certain div container that I create via JavaScript. If I change the following line (inside of "rules" in the .validate call)

"MyTextbox": 
{
  MyMethod: true,
},

to use the ID of the div I created via JavaScript, my custom validation rule will be ignored (the other rules will still apply).

I'm struggling to find the corresponding documentation. It seems that I can only add a rule an input element and not to a div. Am I approaching this the wrong way? How can I add a rule, that appends a message after a certain div-element, if the validation fails?

1
  • "How can I add a rule, that appends a message after a certain div-element, if the validation fails?" ~ Depends... are you validating an input element and need help placing the message or are you looking for a way to validate the div? Commented Sep 21, 2014 at 22:46

1 Answer 1

5

Two important things...

1) You must assign rules by name when using the rules option within .validate(), and every input field must contain a unique name attribute no matter how rules are assigned.

2) Using this plugin, validation can only be applied to input, textarea, and select elements. Period.

Workaround: You could create a type="hidden" input element for validation and use jQuery to copy the relevant value from your div into this hidden field upon a certain triggering event. You can then manually trigger validation using something like $('#myHiddenInput').valid().


For precise error message placement, you would use the errorPlacement callback function. Write a custom function with a conditional for placing the one message.

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

1 Comment

I wasn't aware of the two important things ;) I'm now using an input hidden and added an if/else block into errorPlacement =)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.