3

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?

1
  • 2
    Rather than checking against a blacklist of characters that are not allowed, you might be better checking the string against a whitelist of characters that are allowed, e.g. only allowing alpha-numeric characters. Commented Jun 16, 2009 at 9:23

8 Answers 8

16

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 (+).
Sign up to request clarification or add additional context in comments.

3 Comments

Ummm... except JavaScript regex does not have a match function, only test.
@LawrenceDol: .match() is used on a String, not RegExp. What happens when you tried it?
@Singe : OK, I missed that subtlety. Came here looking for a solution from a regex perspective. Thanks.
5

I would use regular expressions.

See this guide from Mozillla.org. This article does also give a good introduction to regular expressions in JavaScript.

Comments

4

Here is a good article on Javascript validation. Remember you will need to validate on the server side too. Javascript validation can easily be circumvented, so it should never be used for security reasons such as preventing SQL Injection or XSS attacks.

Comments

2

You could learn regular expressions, or (probably simpler if you only check for one character at a time) you could have a list of characters and then some kind of sanitize function to remove each one from the string.

var myString = "An /invalid &string;";
var charList = ['/', '\\', '&', ';']; // etc...

function sanitize(input, list) {
    for (char in list) {
        input = input.replace(char, '');
    }
    return input
}

So then:

sanitize(myString, charList) // returns "An invalid string"

Comments

1

You can use the test method, with regular expressions:

function validString(input){
    return !(/[\\/&;]/.test(input));
}

validString('test;') //false 

Comments

0

You can use regex. For example if your string matches:

[\\/&;]+

then it is not valid. Look at: http://www.regular-expressions.info/javascriptexample.html

Comments

0

You could probably use a regular expression.

Comments

0

As the others have answered you can solve this with regexp but remember to also check the value server-side. There is no guarantee that the user has JavaScript activated. Never trust user input!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.