2012-06-16 44 views
1

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

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

我的失败尝试:

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

和设置:

rules: { 
    input_answer{ 
     required: true, 
     answercheck: true 
    } 

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

任何想法?

+3

? - 不仅如此,他们可以编辑脚本以及 –

+0

你最好使用Ajax发送字符串到PHP页面。 –

回答

0

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

但是,要简单地回答你的问题,这是它是如何完成的。 (这也是一个很好的学习锻炼一下使用addMethod)...

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

而且你也不会需要指定以下answercheck消息,因为它已经在method本身上面定义。 (你还缺少一些支撑{,冒号:和逗号,在此代码。)

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 

Working jsFiddle DEMO

http://jsfiddle.net/ht8Lu/


As per the documentation,你需要构建你自己定制的方法。

添加自定义验证方法。它必须包含一个名称(必须是一个 合法的JavaScript标识符),一个基于javascript的函数和一个默认字符串消息。

参数:

名;字符串用于标识和引用它的方法的名称必须是有效的javascript标识符

方法;回调实际的方法实现,如果元素有效则返回true。第一个参数:当前值。第二个 参数:已验证的元素。第三个参数:参数。

message(可选);字符串,功能要为此方法显示的默认消息。可以是由 jQuery.validator.format(value)创建的函数。如果未定义,则使用已有的 消息(便于本地化),否则必须定义消息必须定义的字段特定消息 。

你知道在客户端验证文本时这样用户可以看到代码,右边