0

I have a form with a text input and I want to validate if the input contains a particular word. I've worked out how to validate for a specific string, but not just a word within that string.

$.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"
   }
 }
})
Community
  • 1
  • 1
Mischa Colley
  • 123
  • 3
  • 13

1 Answers1

0

You can use the indexOf function for this.

indexOf :: returns the position of the string in the other string. If not found, it will return -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}'"));

Please see the working demo https://jsfiddle.net/Prakash_Thete/3tu68rms/

Prakash Thete
  • 3,802
  • 28
  • 28