I want to check if a string contains special characters like !@#$%^&*.,<>/\'";:? and return true if the string contains atleast one of those chars.
I tried with the following regex,script:
var format = /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/;
if( string.match(format) ){
return true;
}else{
return false;
}
If the string contains only the special characters then it returns true , but if the string contains something else like alphanumeric chars ( !example1 , .example2 ) it returns false.
This question is related to
javascript
regex
string
var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";_x000D_
var checkForSpecialChar = function(string){_x000D_
for(i = 0; i < specialChars.length;i++){_x000D_
if(string.indexOf(specialChars[i]) > -1){_x000D_
return true_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
var str = "YourText";_x000D_
if(checkForSpecialChar(str)){_x000D_
alert("Not Valid");_x000D_
} else {_x000D_
alert("Valid");_x000D_
}
_x000D_
Wouldn't it be easier to negative-match alphanumerics instead?
return string.match(/^[^a-zA-Z0-9]+$/) ? true : false;
You can try this:
regex = [\W_]
It will definitely help you.
Your regexp use ^
and $
so it tries to match the entire string. And if you want only a boolean as the result, use test
instead of match
.
var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;
if(format.test(string)){
return true;
} else {
return false;
}
Remove the characters ^
(start of string) and $
(end of string) from the regular expression.
var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
Check if a string contains at least one password special character:
For reference: ASCII Table -- Printable Characters
Special character ranges in the ASCII table are:
Therefore, use this:
/[ -/:-@[-`{-~]/.test(string)
var format = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
// ^ ^
document.write(format.test("My @string-with(some%text)") + "<br/>");
document.write(format.test("My string with spaces") + "<br/>");
document.write(format.test("My StringContainingNoSpecialChars"));
_x000D_
Source: Stackoverflow.com