By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,611 Members | 1,633 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,611 IT Pros & Developers. It's quick & easy.

Checking for illegal characters in a textbox (eg. <,>,!,@,#,$,%,^,&,*,(,) )

P: 24
I have a textbox named "txtName" and a button (btnSave) on a webform.
After I have typed the illegal characters into the textbox and click "Save", I would like the webform to check for those characters and display a message, "Illegal Characters not allowed". How do I achieve that in JavaScript?

Sorry if it seems too simple as I am kinda weak in programming.

Thanks.
Jan 8 '09 #1
Share this Question
Share on Google+
6 Replies


Uncle Dickie
P: 67
You can use the indexOf function to see if the string contains one of your illegal characters e.g.

Expand|Select|Wrap|Line Numbers
  1. var myStr = document.forms[0].txtName.value;
  2. if (myStr.indexOf('<') == -1)
  3. alert('Illegal Characters not allowed');
  4. }
Jan 8 '09 #2

xNephilimx
Expert 100+
P: 213
@Uncle Dickie
Even better, you can use regular expressions, that way you wont have to check for each individual character.

something like:

Expand|Select|Wrap|Line Numbers
  1. if( myStr.match(/[\<\>!@#\$%^&\*,]+/i) ) {
  2.     alert('Illegal characters found!');
  3. }
  4.  
You see that this way you only need one 'if' check, thanks to regex.
Here's a link to a great site if you want to learn more about regex:
Regular-Expressions.info - Regex Tutorial, Examples and Reference - Regexp Patterns
Jan 8 '09 #3

Uncle Dickie
P: 67
Thanks for the link - I had seen code like that and not understood it so glossed over it!
Jan 9 '09 #4

xNephilimx
Expert 100+
P: 213
You're welcome, Uncle Dickie. Since I learnt regexp, I can't live without it XD
Jan 9 '09 #5

P: 24
Thanks alot guys. Really appreciate it. Hope to hear from you guys again.
Cheers! :)
Jan 14 '09 #6

gits
Expert Mod 5K+
P: 5,387
another good page to look at regarding this matter is here ... depending on your needs you should have a look at the 'shortcuts' to match complete character-classes like:

Expand|Select|Wrap|Line Numbers
  1. var s = 'foo>bar';
  2.  
  3. if (/\W/g.test(s)) {
  4.     alert('found a illegal char');
  5. }
  6.  
which uses the \W shortcut to classify the match for all chars that are not contained by the basic latin alphabet ... this often shortens the regExp and make it better readable ...

kind regards
Jan 15 '09 #7

Post your reply

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