Javascript Non Alphanumeric Characters Regex

Using javascript regular expressions to stop users from entering non-aphanumeric characters or white spaces

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

To view a full html sample of the above code click the links below using regular expressions in JavaScript

9 Responses

  1. jonathan

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

    This does not work !

    Here is the correct one :

    /^[0-9a-zA-Z\s]+$/”

    BTW, thanks for your article that saved us bunch of hours !

  2. Pingback: Javascrit Remove Non-Alphanumeric Characters - Good quality PHP, ASP.NET, Ajax and JavaScript script collection and resource blog.

  3. Mark Chaffee

    Since it is regex, wont /\W/ work just as well?

  4. Vipul

    Thanx for your article!!
    This was very much helpful and deftly saved our lot of time..

  5. avo

    Very helpful, thanks. Though restricting character input for passwords is a little silly, and rather insecure.

  6. AfreX

    /\W/ is a nice shortcut, but it excludes the space.

    I used this for alphanumeric and space input only.

    EXAMPLE

    function checkAlphanumeric(v) {
    var regex=/^[0-9a-zA-Zs' ']+$/; //^[a-zA-z' ']+$/
    if(regex.test(v.value)){
    return true;
    } else {
    alert(lng.js_req_alphanumeric)
    return false;
    }
    }

    And for the form input onKeyUp=”return checkAlphanumeric(this)”

    EXAMPLE:

  7. yuvaraj

    In Advance Thanks.The following code works for me with out accepting the wild cards in middle of the string:)

  8. test again@@

    123!! #%>>23d test

  9. iuh

    does not support internationalization!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Next Post » »