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

Stop user from inputing special chars. Only a-z 0-9 allowed.

Markus
Expert 5K+
P: 6,050
How would i go about checking for things such as *,&,%, etc.etc. in a user inputted string.

The code im working on is a sign up script, which i'm trying to make by myself and not use someone elses code, because that just wouldn't benefit my learning of JavaScript.

If you do happen to know how i might do what i want, might you also explain it?

Thanks a bunch.
Nov 10 '07 #1
Share this Question
Share on Google+
4 Replies


100+
P: 428
One way to filter users' text input is to use regular expressions.


Expand|Select|Wrap|Line Numbers
  1. function validText(str){
  2.     return str.replace(/[^a-zA-Z0-9]/g,'');
  3. }
This will remove any characters that are not in the ranges listed in the expression.

You may want to expand the pattern for names, to include

Carroll O'Conner and Edward R. Murrow and Michael Wilkenson-Barre
Nov 10 '07 #2

Markus
Expert 5K+
P: 6,050
One way to filter users' text input is to use regular expressions.


Expand|Select|Wrap|Line Numbers
  1. function validText(str){
  2.     return str.replace(/[^a-zA-Z0-9]/g,'');
  3. }
This will remove any characters that are not in the ranges listed in the expression.

You may want to expand the pattern for names, to include

Carroll O'Conner and Edward R. Murrow and Michael Wilkenson-Barre
So if i were to expand that to include underscores (_) and hyphons (-) i would do this:

Expand|Select|Wrap|Line Numbers
  1. (/[^a-ZA-Z0-9_-]g, '');
  2.  
?

And by the way, it's not that i want to replace the characters, i just want to check for them and alert the user as to the problem.

Thanks for the explanation, aswell!
Nov 10 '07 #3

100+
P: 428
Since the hyphen is used to delimit the range of characters you must escape it by preceding it with a backslash:
/[^\w\-]/

Here the \w is a shortcut often used, it is the pattern described by
/[^a-zA-Z0-9_]/

And the leading caret [^ means match anything NOT in the range described.
Nov 10 '07 #4

Markus
Expert 5K+
P: 6,050
Since the hyphen is used to delimit the range of characters you must escape it by preceding it with a backslash:
/[^\w\-]/

Here the \w is a shortcut often used, it is the pattern described by
/[^a-zA-Z0-9_]/

And the leading caret [^ means match anything NOT in the range described.
Thanks a bunch :)

- mark
Nov 10 '07 #5

Post your reply

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