Vinayak Phal
Vinayak Phal

Reputation: 8919

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

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??" }
}

Upvotes: 11

Views: 2235

Answers (1)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263187

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";
            }
        }
    }
}

Upvotes: 4

Related Questions