javascript code to check special characters

136,702

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

Share:
136,702
ankit
Author by

ankit

Updated on September 21, 2020

Comments

  • ankit
    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 of chkfile.value is desktop.zip in Firefox, but in Chrome the value of chkfile.value is c://fakepath/desktop.zip. How do I get rid of c://fakepath/ from chkfile.value?