469,315 Members | 1,597 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,315 developers. It's quick & easy.

Alert if field contains particular phrase

30
Hi,

I'm a novice and I have the following code, but I can't get it to work. All i want to be able to do is a simple form validation for a single field, so that if the user enters a particular phrase in the field it will display an alert. So if field contains say "hello my name is john" then display an alert.

But I also want it so that it will alert if the phrase is surrounded by other text, e.g. if the user enters the following text in the field "Sir, hello my name is john from earth" it will display the alert, as it contains the phrase "hello my name is john". Here is what i have, but it does not work.

Expand|Select|Wrap|Line Numbers
  1. function checkform (form1)
  2. {    
  3.   if (form1.contact_enquiry.value.indexOf("hello my name is john")==1)
  4.  
  5. {
  6.     alert( "Please enter a valid enquiry." );
  7.     form1.contact_enquiry.focus();
  8.     return false ;
  9.   }
  10.   return true ;
  11. }
Oct 18 '07 #1
2 1714
acoder
16,027 Expert Mod 8TB
Use a regular expression, e.g.
Expand|Select|Wrap|Line Numbers
  1. form1.contact_enquiry.value.match(/hello my name is john/)
Oct 18 '07 #2
mrhoo
428 256MB
if (form1.contact_enquiry.value.indexOf("hello my name is john")==1)
Strings are zero based- in your code, the index is 0, not 1.

To just find if the exact string is included, test that that index is not -1,
which is the return value if the string is not found.

acode's use of regular expressions is much more powerful- you can find a pattern, like any name in the value, and not just a single instance.
Oct 18 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

6 posts views Thread by bonehead | last post: by
11 posts views Thread by Bradford Chamberlain | last post: by
1 post views Thread by vauneen | last post: by
10 posts views Thread by dimple.nshah | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by harlem98 | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.