Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  80] [ 5]  / answers: 1 / hits: 52781  / 15 Years ago, tue, june 16, 2009, 12:00:00

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?


More From » regex

 Answers
53

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 (+).


[#99307] Thursday, June 11, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aubriea

Total Points: 641
Total Questions: 118
Total Answers: 101

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
aubriea questions
Sun, Apr 26, 20, 00:00, 4 Years ago
Sun, May 26, 19, 00:00, 5 Years ago
Wed, Mar 27, 19, 00:00, 5 Years ago
;