0

The text validation in jquery, String contains exact substring not partial. Ex: Input String : Hello World Sub String : Hello There are validation in like str.indexof(SubString) >-1 or /SubString/.test(str) If some one enters He in the input text box it validates the above condition where it should validate exact string "Hello" not for He. How to do this. Your suggestion will be highly appreciated.

/Hello/.test(Hello World) - correct validation as Hello World

/Hello/.test(He..) - It should n't validate, Where it validates for He llo in He..

 setValidation: function(){
 $.validator.addMethod("no_Hello_word", function(value) {
              return /hello/.test(value) || /HELLO/.test(value);
          }, "Text mustn't contain word hello/HELLO");
}
1
  • use word boundaries.. Commented Aug 29, 2014 at 3:37

5 Answers 5

1

try

return !/hello/i.test(value) || /Hello/.test(value)

Sign up to request clarification or add additional context in comments.

Comments

0

why don't you do it like this? This should not validate if the user puts in "he"

var string= "hello, world";
var string_array= string.toLowerCase().split(" ");

if (string_array.indexOf("hello") >= 0){
    return true;
} else {
    return false;
}

1 Comment

it neither check for exact word.instead hello if you put he and check indexof it will return same index i.e it just checks the index matched letter.
0

what about this: split the string by spaces and then search in the array the word:

var exactSearch = function(word, string){
    var words = string.split(" ");

    for(i = 0; i < words.length; i++){
        if(word == words[i]){
            return true;
        }
    }
    return false;
}

See the working example here

UPDATE

I think I write the answer before you edit the question.

Maybe it works for you:

$.validator.addMethod("no_Hello_word", function(value, element) {
    return (value.toLowerCase && (value.toLowerCase() === "hello"));
},
    "Text mustn't contain word hello/HELLO!"
);

Comments

0

Try this:

function isValid(str){ 
    return !/[hH]ello/.test(str); 
}

// isValid('Hello') -> false
// isValid('Hello World') -> false
// isValid('He') -> true

You can flip this if you want the validation to be other way round.

Comments

0
$.validator.addMethod("helloworld_word", function(value,element) {
              return /^((?!helloworld).)*$/i.test(value);
 }, "No Hello world");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.