We help IT Professionals succeed at work.

JS Special Character Valitation

Chadd C
Chadd C asked
I am attempting to include  [  ]  $  ?  \  in the below snippet. I tried to escape them to no avail. What is the proper syntax for this string?

   
function validate_desc(val){
        if ( val.match("^[a-zA-Z0-9,-. \\\\/(/)#/_/'\":]+\$") ) {
            return true;
        } else {
            return false;
        }
    }

Open in new window

Comment
Watch Question

SILVER EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019
You just add them as escaped characters \$ \? \\ (which you already have) \[ \] and don't escape the $ at the end that is your end of line indicator
Also don't enclose your regex in "" rather use the regex delimiters  / /
You can also use the \w instead of a-zA-Z0-9_
function validate_desc(val){
  if ( val.match(/^[\[ \-,\w\?\$\]\\\/\(\)]+$/) ) {
    return true;
  } else {
    return false;
  }
}

Open in new window

ZvonkoSystems architect
BRONZE EXPERT
Top Expert 2006
Check this:
function validate_desc(val){
      var inv = val.match(/[^\w\,\-\.\ \\\/\(\)\#\'\"\:]/g);
        if ( inv ) {
         console.log("Invalid chars: "+inv.join(' '));
            return false;
        } else {
            return true;
        }
    }

It return  false  if  any character is found tht is NOT in this list:  \w , - . blank \ / ( ) # ' " :