Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??" }
}
like image 852
Vins Avatar asked Jul 13 '12 07:07

Vins


1 Answers

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";
            }
        }
    }
}
like image 88
Frédéric Hamidi Avatar answered Nov 15 '22 19:11

Frédéric Hamidi