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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can solve this with regular expressions!
matching against the regex returns the string if it is ok, or null if its invalid!
Explanation:
/‘s) instead of quotes ("‘s).validRegExcause 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.[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.\\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).&) has no special meaning and is unescaped.*) 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 (+).