jquery验证插件自定义规则检查单词

jquery validation plugin custom rule check for a word

我需要为Jquery Validation插件创建一个自定义规则来检查一个特定的单词。

在这种情况下,用户必须通过在输入字段中输入单词"cat"来正确回答问题。 自定义规则需要将答案定义为"cat",我将其视为变量,然后检查它。

我失败的尝试:

1
2
3
4
jQuery.validator.addMethod("answercheck", function(value, element) {
  var password = string('hot');
  return value(password);
},"Type the correct answer");

和设置:

1
2
3
4
5
6
7
8
9
10
11
rules: {
    input_answer{
        required: true,
        answercheck: true
    }

messages: {
    input_answer{
        required:"Answer the question",
        answercheck:"Your answer is incorrect"
    }

有任何想法吗?


正如其他人所说,这不是一种安全的方法,因为任何人都可以看到/操纵JavaScript并轻松绕过它。

但是,要简单回答您的问题,这就是它的完成方式。 (这也是关于使用addMethod的一个很好的学习练习)...

1
2
3
jQuery.validator.addMethod('answercheck', function (value, element) {
    return this.optional(element) || /^\bcat\b$/.test(value);
},"Type the correct answer");

而且您也不需要为下面的answercheck指定消息,因为它已经在method本身内部定义。 (您在此代码中也缺少一些大括号{,冒号:和逗号,。)

1
2
3
4
5
6
7
8
9
10
11
12
rules: {
    input_answer: { // <- missing colon after input_answer
        required: true,
        answercheck: true
     }
}, // <- missing brace & comma
messages: {
    input_answer: { // <- missing colon after input_answer
        required:"Answer the question"
        //, answercheck:"Your answer is incorrect"  // not needed, specified in method
    }
} // <- missing brace and maybe a comma depending on what follows

工作jsFiddle DEMO:

http://jsfiddle.net/ht8Lu/

根据文档,您需要构建自己的自定义方法。

Add a custom validation method. It must consist of a name (must be a
legal javascript identifier), a javascript based function and a
default string message.

Arguments:

name; String The name of the method, used to identify and referencing it, must be a valid javascript identifier

method; Callback The actual method implementation, returning true if an element is valid. First argument: Current value. Second
argument: Validated element. Third argument: Parameters.

message (Optional); String, Function The default message to display for this method. Can be a function created by
jQuery.validator.format(value). When undefined, an already existing
message is used (handy for localization), otherwise the field-specific
messages have to be defined.