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

You may also like...

10 Responses

  1. jonathan says:

    “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. Mark Chaffee says:

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

  3. Vipul says:

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

  4. avo says:

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

  5. AfreX says:

    /\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:

  6. yuvaraj says:

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

  7. test again@@ says:

    123!! #%>>23d test

  8. iuh says:

    does not support internationalization!

  9. James Rolan says:

    You should use a live regex tester like liveregex.com. It support PHP, Ruby, Python and have a diagram that explains the regex for you for it’s easier to understand. You can generate a permalink to share the regex too. 😀 I love it and hope it’s useful for you.

Leave a Reply