Javascript regexp - only if first character is not an asterisk

Splynx picture Splynx · Mar 14, 2011 · Viewed 41.5k times · Source

I am using a javascript validator which will let me build custom validation based on regexp

From their website: regexp=^[A-Za-z]{1,20}$ allow up to 20 alphabetic characters.

This will return an error if the entered data in the input field is outside this scope.

What I need is the string that will trigger an error for the inputfield if the value has an asterix as the first character.

I can make it trigger the opposite (an error if the first character is NOT an asterix) with:

regexp=[\u002A]

Heeeeelp please :-D

Answer

Cameron picture Cameron · Mar 14, 2011

How about:

^[^\*]

Which matches any input that does not start with an asterisk; judging from the example regex, any input which does not match the regex will be cause a validation error, so with the double negative you should get the behaviour you want :-)

Explanation of my regex:

  • The first ^ means "at the start of the string"
  • The [ ... ] construct is a character class, which matches a single character among the ones enclosed within the brackets
  • The ^ in the beginning of the character class means "negate the character class", i.e. match any character that's not one of the ones listed
  • The \* means a literal *; * has a special meaning in regular expressions, so I've escaped it with a backslash. As Rob has pointed out in the comments, it's not strictly necessary to escape (most) special characters within a character class