I'm using the plugin of validation in jquery. There is a very strange thing is that, when I add rules in this way
$(document).ready(function () {
$.validator.addMethod("endDateGreaterThan", function (value, element, params) {
if (value != "" && $(params).val() != "") {
var endDate = formatValidateDate(value);
var startDate = formatValidateDate($(params).val());
if (startDate == null || endDate == null)
return true;
return new Date(endDate) >= new Date(startDate);
}
return true;
}, "");
var validator = $("#form").validate({
rules: {
StartDate: "required",
EndDate: {
required: true,
endDateGreaterThan: "#StartDate"
},
DiscountRate: {
required: true,
max: 100,
min: 1
}
},
messages: {
StartDate: {
required: "ErrorMessageStartDateRequired"
},
EndDate: {
required: "ErrorMessageEndDateRequired",
endDateGreaterThan: "ErrorMessageEndDateGreaterThanStartDate"
},
DiscountRate: {
required: "ErrorMessageDiscountRateRequired",
max: "Global.ErrorMessageDiscountRateRange",
min: "Global.ErrorMessageDiscountRateRange"
}
}
});
There is no rule added. If I debug the js file and step into the validate method in jquery.validation.js file, I found that the option passed to validate method is empty.
But If I add rules dynamically, just like
$("#StartDate").rules("add", {
required: true,
messages: {
required: "StartDate is required"
}
});
The rule will be added just as what it should be.
I'm using ASP.net mvc.
Any suggestions are appreciate.
form. In your first case, whenrulesare defined within.validate(), you must use thenameattribute as the selector. In your second case, with therules('add')method, you're targeting your field by itsidattribute. See the difference? If we could see the HTML of the form, would yourrulesselectors match the fields'nameattribute?