Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript code to check special characters

Tags:

javascript

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?

like image 219
ankit Avatar asked Aug 10 '12 06:08

ankit


People also ask

How do you check if a character is a special character in JavaScript?

To check if a string contains special characters, call the test() method on a regular expression that matches any special character. The test method will return true if the string contains at least 1 special character and false otherwise. Copied!

How do you find special characters?

Click Start, point to Settings, click Control Panel, and then click Add/Remove Programs. Click the Windows Setup tab. Click System Tools (click the words, not the check box), and then click Details. Click to select the Character Map check box, click OK, and then click OK.

How do you check if a string contains a set of characters in JavaScript?

You can check if a JavaScript string contains a character or phrase using the includes() method, indexOf(), or a regular expression. includes() is the most common method for checking if a string contains a letter or series of letters, and was designed specifically for that purpose.


1 Answers

You can test a string using this regular expression:

function isValid(str){  return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str); } 
like image 157
KooiInc Avatar answered Oct 21 '22 08:10

KooiInc