11

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")

}
user1801279
  • 1,743
  • 5
  • 24
  • 40
  • 5
    What is the question? – tjons Nov 12 '13 at 15:04
  • You can try `/[^a-zA-Z0-9]/.test( str )` which will return true if any characters at not in a-Z, A-Z or 0-9 but note this will also treat `é` or similar character as rejected symbols – megawac Nov 12 '13 at 15:18

3 Answers3

23

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");
}
Manik Arora
  • 4,702
  • 1
  • 25
  • 48
megawac
  • 10,953
  • 5
  • 40
  • 61
3

This may be helpful. javascript regexp remove all special characters if the only characters you want are numbers, letters, and ',' then you just need to whitespice all characters that are not those

$(this).val().replace(/[^\w\s\][^,]/gi, '')

Community
  • 1
  • 1
michael truong
  • 321
  • 1
  • 4
1

This link may be helpful:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

It has a lot of information on JS Regexps.

For a dollar sign ($), the regexp syntax would be: \$. You need to escape the special character so it is read as a literal. The syntax would be the same for the other special characters, I believe.

tjons
  • 4,749
  • 5
  • 28
  • 36