jQuery Validate:不是默认值 [英] jQuery Validate: Not default value

查看:133
本文介绍了jQuery Validate:不是默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单中有一个类别下拉选择元素.表单已通过jQuery验证,如下所示:

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

加载页面时,类别的默认值为:'---'(不带引号).当我提交表格时,验证说一切都可以,因为"---"不是什么.如果将"---"用作类别,如何停止提交?其他类别如下:Category1.必须选择一种可能性,而我无法更改下拉选择项.

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.

谢谢!

推荐答案

您可以添加自定义规则,如下所示:

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!");

然后在您的rules中使用该规则,如下所示:

Then use that rule in your rules, like this:

    category: {
        required: true,
        notEqual: "---"
    }

您可以在此处进行测试.

这篇关于jQuery Validate:不是默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆