我的表单中有一个类别下拉选择元素。该表单使用jQuery进行验证,如下所示:
$('#myForm').validate({
rules: {
text: {
required: true
},
category: {
required: true
}
},
messages: {
text: {
required: "Text required"
},
category: {
required: "Category required"
}
}
加载页面时,类别的默认值为:'---'(不带引号)。当我提交表格时,验证说eveything是可以的,因为'---'并非一无是处。当'---'用作类别时,如何让它停止提交?其他类别是这样的:Category1。必须选择其中一种可能性,我无法更改下拉选择内容。
谢谢!
答案 0 :(得分:13)
您可以添加自定义规则,如下所示:
jQuery.validator.addMethod("notEqual", function(value, element, param) {
return this.optional(element) || value !== param;
}, "Please choose a value!");
然后在rules
中使用该规则,如下所示:
category: {
required: true,
notEqual: "---"
}
答案 1 :(得分:0)
我在MVC视图中使用了来自http://jqueryvalidation.org/的插件并修改如下:
注意:使用下拉项时 - >值:0,文字: - 请选择 -
- >添加自定义所需类型
//====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.",....
- &gt;添加自定义所需方法
//====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 ) {
....
- &gt;页面上的脚本
$("#frmSave").validate({
//set required fields
rules: {
ITEM_TYPE: {
required: true ,
noDefaultVal: "0"
}
}
});
方面。