2016-03-24 44 views
1

我有一個文本輸入的表單,我想驗證輸入是否包含一個特定的單詞。我已經制定了如何驗證specific string,但不僅僅是該字符串中的單詞。jQuery驗證 - 驗證字符串的內容

$.validator.addMethod("exampleword", function(value, element, string) { 
return value === string; 
}, $.validator.format("Please enter '{0}'")); 

$("#example-form").validate({ 
rules: { 
    address: { 
    required: true, 
    exampleword: "Foo" 
    } 
}, 
messages: { 
    address: { 
    required: "Please enter an address", 
    exampleword: "Please include Foo" 
    } 
} 
}) 

回答

0

您可以使用indexOf函數。

indexOf ::返回字符串在另一個字符串中的位置。如果沒有找到,它會返回-1

//Assuming "string" is the word you are looking in your input 
$.validator.addMethod("exampleword", function(value, element, string) { 
    return value.indexOf(string) > -1 ; 
}, $.validator.format("Please enter '{0}'")); 

請參閱工作演示https://jsfiddle.net/Prakash_Thete/3tu68rms/