user1801279 user1801279 - 4 years ago 248
Javascript Question

Regex to not allow special characters (Javascript)

I have a following requirement to only allow capital letters and , in a javascript form . I am unsure on how to check for special characters and script tags . I have written the following code . I do not want to allow characters such as $,%,& etc .

var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('^[a-z]');
var numbers = new RegExp('^[0-9]');

if($(this).val().match(upperCase) && $(this).val().match(lowerCase) && $(this).val().match(numbers))
{
$("#passwordErrorMsg").html("OK")

}

Answer Source

Based on what you've given us, this may suit the bill. It will determine if any characters are not in character classes a-z, A-Z or 0-9 but note this will also treat é or similar characters as rejected symbols.

So if the value is 'test_' or 'test a' it will fail but it will pass for 'testa'. If you want it to accept spaces change the regex to /[^a-zA-Z0-9 ]/.

if(!/[^a-zA-Z0-9]/.test($(this).val())) {
    $("#passwordErrorMsg").html("OK");
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download