Search code examples
javascriptregexvalidation

Javascript String pattern Validation


I have a string and I want to validate that string so that it must not contain certain characters like '/' '\' '&' ';' etc... How can I validate all that at once?


Solution

  • You can solve this with regular expressions!

    mystring = "hello"
    yourstring = "bad & string"
    
    validRegEx = /^[^\\\/&]*$/
    
    alert(mystring.match(validRegEx))
    alert(yourstring.match(validRegEx))
    

    matching against the regex returns the string if it is ok, or null if its invalid!

    Explanation:

    • JavaScript RegEx Literals are delimited like strings, but with slashes (/'s) instead of quotes ("'s).
    • The first and last characters of the validRegEx cause it to match against the whole string, instead of just part, the carat anchors it to the beginning, and the dollar sign to the end.
    • The part between the brackets ([ and ]) are a character class, which matches any character so long as it's in the class. The first character inside that, a carat, means that the class is negated, to match the characters not mentioned in the character class. If it had been omited, the class would match the characters it specifies.
      • The next two sequences, \\ and \/ are backslash escaped because the backslash by itself would be an escape sequence for something else, and the forward slash would confuse the parser into thinking that it had reached the end of the regex, (exactly similar to escaping quotes in strings).
      • The ampersand (&) has no special meaning and is unescaped.
    • The remaining character, the kleene star, (*) means that whatever preceeded it should be matched zero or more times, so that the character class will eat as many characters that are not forward or backward slashes or ampersands, including none if it cant find any. If you wanted to make sure the matched string was non-empty, you can replace it with a plus (+).