28

I have a kinda wierd problem. I want to trigger a jquery-valdation errormessage on an element even thou it's valid.

Scenario: I have a large form. One of the inputs is for PersonalId. It's optional to enter that PersonalId. Beside that input i have a normal button (not the submit-button). If you click on that (fetching information from ajax) and the PersonalId field is empty i want to trigger that Error-message.

Is that possible with jQuery Validate or do i need to create my own function?

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
mannge
  • 371
  • 1
  • 5
  • 12
  • Possible duplicate of [Manually set unobtrusive validation error on a textbox](https://stackoverflow.com/questions/7380278/manually-set-unobtrusive-validation-error-on-a-textbox) – KyleMit Nov 20 '17 at 23:05

1 Answers1

58

Is that possible with jQuery Validate or do i need to create my own function?

Both, sort of. You can use the showErrors function to display errors on the form manually, but since you don't want this to be a rule that is enabled when you submit the form, you'll have to do your own checking for the value in the input.

Something like:

var $validator = $("#myform").validate();
$("#checkid").click(function() {
    var errors;

    if (!$("#personalid").val()) {
        /* Build up errors object, name of input and error message: */
        errors = { personalid: "Please enter an ID to check" };
        /* Show errors on the form */
        $validator.showErrors(errors);            
    }        
});

Example: http://jsfiddle.net/andrewwhitaker/XjZer/

Note that the form will still submit if there is nothing in the personalid field.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • I have same problem but how can I trigger error for multidimentional name. I could not solve this by your solution. e.g. `field = "email"; var element = "data[User]["+field+"]"; errors = { element : field_error }; $validator.showErrors(errors);` – Parixit Nov 30 '15 at 06:32
  • Uncaught TypeError: $(...).validate is not a function – shamaseen Jan 26 '21 at 22:57