Mannu
Mannu

Reputation: 71

Regular Expression for only one character(*) or other alphanumeric

I have a condition in regex, the limit is 8 character and it should accept number, alphabet and ? and if we entered * in field it should give error.

or if we typing * in input filed.it should accept only one * for whole field, none other than that.

eg: * is equivalent to wer?23w4

regex is:

/[a-zA-Z0-9?]{8}/

Upvotes: 0

Views: 1480

Answers (2)

lc.
lc.

Reputation: 116458

You can use the alternation operator (|) to specify an either-or condition. In your case:

/\*|[a-zA-Z0-9?]{8}/

This means to match either:

  • A single * character, nothing else
  • Or, exactly eight characters consisting of lowercase, uppercase, digits, or ?.

Note, depending on how you are using this in code, you probably need to add the anchors ^ and $, to make sure it tests against the entire field:

/^(?:\*|[a-zA-Z0-9?]{8})$/

Regular expression visualization

Debuggex Demo

Upvotes: 3

gurvinder372
gurvinder372

Reputation: 68393

try

 /(\*|[a-zA-Z0-9\?]{8})/g

for example

"33asdsad".match( /(\*|[a-zA-Z0-9\?]{8})/g); 

and

"*".match( /(\*|[a-zA-Z0-9\?]{8})/g)

and

"234234?d".match( /(\*|[a-zA-Z0-9\?]{8})/g)

Upvotes: 0

Related Questions