I have a category dropdown selection element in my form. The form is validated with jQuery as follows:
$('#myForm').validate({
rules: {
text: {
required: true
},
category: {
required: true
}
},
messages: {
text: {
required: "Text required"
},
category: {
required: "Category required"
}
}
When loading the page, the default value of category is: '---' (without quotes). When I submit the form, the validation says eveything is ok, because '---' is not nothing. How can I开发者_高级运维 get it to stop submitting when '---' is used as category? The other categories are something like this: Category1. One of the possibilities have to be choosen and I can't change the dropdown selection thing.
Thanks!!
You could add a custom rule, like this:
jQuery.validator.addMethod("notEqual", function(value, element, param) {
return this.optional(element) || value !== param;
}, "Please choose a value!");
Then use that rule in your rules
, like this:
category: {
required: true,
notEqual: "---"
}
You can test it out here.
I used plugin from http://jqueryvalidation.org/ in MVC view and modified as below :
note: using when dropdown item -> value: 0, text: --Please Select--
-->add custom required type
//====find "message {: ..."
messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",....
//====modify to
messages: {
noDefaultVal: "This field is required.", //<-- modified
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",....
-->add custom required method
//====and find "methods: {: ..."
methods: {
// http://docs.jquery.com/Plugins/Validation/Methods/required
required: function( value, element, param ) {
// check if dependency is met
if ( !this.depend(param, element) ) {....
//====modify to
methods: {
noDefaultVal: function (value, element, param) {
return this.optional(element) || value != param;
},
// http://docs.jquery.com/Plugins/Validation/Methods/required
required: function( value, element, param ) {
....
-->on-page script
$("#frmSave").validate({
//set required fields
rules: {
ITEM_TYPE: {
required: true ,
noDefaultVal: "0"
}
}
});
Regard.
精彩评论