javascript code to check special characters
Solution 1
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Solution 2
Directly from the w3schools website:
var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);
To combine their example with a regular expression, you could do the following:
function checkUserName() {
var username = document.getElementsByName("username").value;
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
if (pattern.test(username)) {
alert("Please only use standard alphanumerics");
return false;
}
return true; //good user input
}
Solution 3
Try This one.
function containsSpecialCharacters(str){
var regex = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;
return regex.test(str);
}
Solution 4
Did you write return true
somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
Solution 5
You could also do it this way.
specialRegex = /[^A-Z a-z0-9]/
specialRegex.test('test!') // evaluates to true
Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character
ankit
Updated on September 21, 2020Comments
-
ankit over 3 years
I have JavaScript code to check if special characters are in a string. The code works fine in Firefox, but not in Chrome. In Chrome, even if the string does not contain special characters, it says it contains special characters.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?"; for (var i = 0; i < chkfile.value.length; i++) { if (iChars.indexOf(chkfile.value.charAt(i)) != -1) { alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n"); return false; } }
Suppose I want to upload a file
desktop.zip
from any Linux/Windows machine. The value ofchkfile.value
isdesktop.zip
in Firefox, but in Chrome the value ofchkfile.value
isc://fakepath/desktop.zip
. How do I get rid ofc://fakepath/
fromchkfile.value
?