Check an Input with jQuery. Contains()

I want to validate a form with jQuery. So I need to check if an input field ("#validatename") does not contain few words, like 'United States of America', 'United Kingdom' or 'France' for instance.

To forbidden 'United States of America" (I'll see later for an array with all forbidden strings!), I have...

$("#validatename").keyup(function()
{
 var name = $("#validatename").val();
 if(name != '')
 {
   if ($('#validatename:contains("United States of America")').length > 0) // 
   {
    $("#validatename").css({
    "background-image": "url('no.png')"
    });
   }
   else
   {
    $("#validlastname").css({
    "background-image": "url('yes.png')"
    });
   }
 }
}

... But it doesn't work: yes.png is always displaying!

Any help or idea will be greatly appreciated!

Thanks a lot.

2 Answers

try

$("#validatename").val().indexOf("United States of America") > -1
0

instead of

$('#validatename:contains("United States of America")').length > 0

you can use

name.indexOf("United States of America") != -1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest