i have a string... i want to validate that string so that it should not contain certain characters like '/' '\' '&' ';' etc... how can i do that all at once???
I would use regular expressions.
See this guide from Mozillla.org. This article does also give a good introduction to regular expressions in JavaScript.
You can use regex. For example if your string matches:
[\\/&;]+
then it is not valid. Look at: http://www.regular-expressions.info/javascriptexample.html
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 next two sequences,
- 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 (+
).
You can use the test method, with regular expressions:
function validString(input){
return !(/[\\/&;]/.test(input));
}
validString('test;') //false
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"
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!