jogesh_pi
jogesh_pi

Reputation: 9782

Regex for alphanumeric and special characters in jquery

i tried to make a regex for my Address column the code is:

var str = "97sadf []#-.'";
var regx = /^[a-zA-z0-9\x|]|[|-|'|.]*$/;

if(str.match(regx))
   document.write('Correct!');
else
    document.write('Incorrect!');

the special character i want that is ][#-. the given code return me the correct match but if i add another kind of the special character like @% then the correct result i got, but i want the incorrect result.

i don't know where i did wrong please help me to make right..

EDIT: Sorry guys but the one thing i have to discuss with you that is there is no necessary to enter the special characters that i mentioned ][#-., but if the someone enter other then the given special character then should return the incorrect.

Upvotes: 1

Views: 12182

Answers (1)

mynameiscoffey
mynameiscoffey

Reputation: 15982

The correct regex (assuming you want uppercase letters, lowercase letters, numbers, spaces and special characters [].-#') is:

var regx = /^[a-zA-Z0-9\s\[\]\.\-#']*$/

There are a couple things breaking your code.

First, [, ], - and . have special meaning, and must be escaped (prefixed with \).

\x checks for line breaks, where we want spaces (\s).

Next, lets look at the structure; for simplicity's sake, lets simplify to ^[abc]|[def]*$. (abc and def being your two blocks of character types). Since the * is attached to the second block, it is saying one instance of [abc] or any number of [def].

Finally, we don't need | inside of brackets, becuase they already mean one character contained within them (already behaves like an or).

Upvotes: 3

Related Questions