hemc4
hemc4

Reputation: 1633

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?

Upvotes: 4

Views: 80182

Answers (4)

Amit
Amit

Reputation: 536

use this this will fix the issue

String patttern = r"[!-/:-@[-`{-~]";

RegExp regExp = RegExp(patttern);

Upvotes: 0

Arshad
Arshad

Reputation: 343

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

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

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

Upvotes: 3

Munavar
Munavar

Reputation: 11

Use the below function

function checkSpcialChar(event){
    if(!((event.keyCode >= 65) && (event.keyCode <= 90) || (event.keyCode >= 97) && (event.keyCode <= 122) || (event.keyCode >= 48) && (event.keyCode <= 57))){
        event.returnValue = false;
        return;
    }
    event.returnValue = true;
}

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

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 */ }

Upvotes: 17

Related Questions