Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to restrict special characters

i have an address field in my form and i want to restrict
* | \ " : < > [ ] { } \ ( ) '' ; @ & $
i have tried with

var nospecial=/^[^* | \ " : < > [ ] { } ` \ ( ) '' ; @ & $]+$/;
            if(address.match(nospecial)){
                alert('Special characters like * | \ " : < > [ ] { } ` \ ( ) \'\' ; @ & $ are not allowed');
                return false;

but it is not working. Please tell me what i missed?

like image 851
hemc4 Avatar asked Oct 23 '25 05:10

hemc4


2 Answers

You need to escape the closing bracket (as well as the backslash) inside your character class. You also don't need all the spaces:

var nospecial=/^[^*|\":<>[\]{}`\\()';@&$]+$/;

I got rid of all your spaces; if you want to restrict the space character as well, add one space back in.

EDIT As @fab points out in a comment, it would be more efficient to reverse the sense of the regex:

var specials=/[*|\":<>[\]{}`\\()';@&$]/;

and test for the presence of a special character (rather than the absence of one):

if (specials.test(address)) { /* bad address */ }
like image 130
Ted Hopp Avatar answered Oct 25 '25 20:10

Ted Hopp


/[$&+,:;=?[]@#|{}'<>.^*()%!-/]/

below one shouldn't allow to enter these character and it will return blank space

.replace(/[$&+,:;=?[\]@#|{}'<>.^*()%!-/]/,"");
like image 27
Arshad Avatar answered Oct 25 '25 20:10

Arshad