5

I need to validate a field with multiple conditions with different error messages. How could I fix this?

$.validator.addMethod("customMethod", function(value, element) {
    var msg;
    if(cond1){
       msg = "msg1";
    }
    else if(cond2){
       msg = "msg2";
    }
    else if(cond3){
       msg = "msg3";
    }
}, msg);
3
  • could you provide with a jsfiddle please? Commented Jan 21, 2016 at 2:45
  • I could not pass out the msg as it is undefined at the end. Commented Jan 21, 2016 at 2:48
  • Did you try adding breakpoints and checking what is the value, before the 'if' exits? Commented Jan 21, 2016 at 2:49

1 Answer 1

7

You would have to pass in an anonymous function in the message parameter, because you just cannot pass msg from the result of the previous anonymous function to the next parameter (as msg, in your context, only exists within that particular anonymous function scope).

$.validator.addMethod("customMethod", function(value, element) {
    // Do your usual stuff here.
}, function (params, element) {
    var msg;
    if(cond1){
       msg = "msg1";
    }
    else if(cond2){
       msg = "msg2";
    }
    else if(cond3){
       msg = "msg3";
    }
    return msg;
});

However, you could just declare msg in the global scope like this:

var msg;
var dynamicErrorMsg = function () { return msg; }
$.validator.addMethod("customMethod", function(value, element) {
    if(cond1){
       msg = "msg1";
    }
    else if(cond2){
       msg = "msg2";
    }
    else if(cond3){
       msg = "msg3";
    }
}, dynamicErrorMsg);

And this would work as well.

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

2 Comments

thanks, it works like a charm.
Works like a charm for the first solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.