Posted by: prajapatinilesh | September 20, 2007

Javascript Non Alphanumeric Characters Regex

Say you want to stop users from entering non-aphanumeric characters or white spaces.
Using regular expressions would be the easiest method:
Here is my javascript code:
<script language="Javascript">
function alphaNumericCheck(){
var regex=/^[0-9A-Za-z]+$/; //^[a-zA-z]+$/
if(regex.test(document.add_data.password.value)){
alert("Good")
return true;
} else {
alert("Please fix: password")
return false;
}
}
</script>

For numbers only use /^[0-9]+$/
For mixed text and numbers, with spaces /^[0-9a-zA-Zs]+$/
Here are more useful regular expressions:
[a-zA-Z] any letter
d any number; same as [0-9]
D any NOT number; same as [^0-9]
w any alphanumeric character; same as [a-zA-Z-0-9_]
W any NON-alphanumeric character; same as [^a-zA-Z0-9_]
s any whitespace (tab, space, newline, etc...)
S any NON-whitespace
n newline
t tab

Advertisements

Responses

  1. Hi, Nilesh
    Jay Gujarat
    Jah Hind

  2. What about accented characters such as Ááéëê ? Your solution does not do those…..

  3. Hi Nilesh,

    I tried For mixed text and numbers, with spaces /^[0-9a-zA-Zs]+$/

    It still did not allow space.

  4. For mixed text and numbers, with spaces /^[0-9a-zA-Zs]+$/

    does not work if “s ” is used for space but ” ” works.

  5. Really very useful blog.

    Thanks dear Nilesh

    Paresh Rathod

  6. It is good but how can we express these(:,-.) symbols in alphanumeric regular expression
    for example:
    H-No:1-343/1,
    plot no:45

  7. thank you Nilesh and I am awaiting for your response

  8. Tanks


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: