11

jQuery Validate, How to give custom error from the custom function based on the different condition???.

Here is the sample code. This is not my actual code. Here I'm trying to put my problem in the sample code.

I've modified the default required functionality with custom function. But how can i give the proper message based on the different conditions.

rules: {
    "data[Model][field1]": {
        required:function(){
            var myValue = $('#myfield').val();
            if( myValue < '5') {
                // Here i want to assign different error message
                return false;
            } else if( myValue > '10') {
                // Here i want to assign different error message
                return false;
            } else {
                return true;
            }
        }
    },
messages: {
    "data[Model][field1]":{ "required":"How can i get the above messages here??" }
}
1
  • $.extend($.validator.messages, { required: "Required" }); Commented Jul 13, 2012 at 7:54

1 Answer 1

4

The messages option can take functions that return the error messages, so you can write something like:

rules: {
    "data[Model][field1]": {
        required: function() {
            var myValue = $("#myfield").val();
            return myValue >= 5 && myValue <= 10;
        }
    }
},
messages: {
    "data[Model][field1]": {
        required: function() {
            var myValue = $("#myfield").val();
            if (myValue < 5) {
                return "Value must be greater than 4";
            } else if (myValue > 10) {
                return "Value must be less than 11";
            }
        }
    }
}
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.