2012-06-16 75 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)創建的函數。如果未定義,則使用已有的 消息(便於本地化),否則必須定義消息必須定義的字段特定消息 。

你知道在客戶端驗證文本時這樣用戶可以看到代碼,右邊