2016-03-24 42 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/