Ragesh Pikalmunde
Ragesh Pikalmunde

Reputation: 1403

Regex to accept special character only in presence of alphabets or numeric value in JavaScript?

I have a Javascript regex like this:

/^[a-zA-Z0-9 !@#$%^&*()-_-~.+,/\" ]+$/

which allows following conditions:

  1. only alphabets allowed

  2. only numeric allowed

  3. combination of alphabets and numeric allowed

  4. combination of alphabets, numeric and special characters are allowed

I want to modify above regex to cover two more cases as below:

only special characters are not allowed

string should not start with special characters

so basicaly my requirement is:

string = 'abc' -> Correct
string = '123' -> Correct
string = 'abc123' ->Correct
string = 'abc123!@#' ->Correct
string = 'abc!@#123' -> Correct
string = '123!@#abc' -> Correct

string = '!@#' -> Wrong
string = '!@#abc' -> Wrong
string = '!@#123' -> Wrong
string = '!@#abc123' -> Wrong

can someone please help me with this?

Upvotes: 2

Views: 1472

Answers (3)

Van Minh Nhon TRUONG
Van Minh Nhon TRUONG

Reputation: 99

If all the special characters are allowed and you consider that underscore _ is also a special character then you can always simplify your RegEx like this :

/^[^\W_].+$/

Check here for your given examples on Regex101

Upvotes: 0

zer00ne
zer00ne

Reputation: 43870

Just add [a-zA-Z0-9] to the beginning of the regex:

/^[a-zA-Z0-9][a-zA-Z0-9 \^\\\-!@#$%&*()_~.+,/'"]+$/gm

Note, if within a class (ie [...]) that there are four special characters that must be escaped by prefixing a backward slash (\) to it so that it is interpreted as it's literal meaning:

// If within a class (ie [...])
^ \ - ]
// If not within a class
\ ^ $ . * + ? ( ) [ ] { } |

RegEx101

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

You can require at least one alphanumeric:

/^(?=[^a-zA-Z0-9]*[a-zA-Z0-9])[a-zA-Z0-9 !@#$%^&*()_~.+,/\" -]+$/
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Also, I think you wanted to match a literal -, so need to repeat it, just escape, change -_- to \-_, or - better - move to the end of the character class.

The (?=[^a-zA-Z0-9]*[a-zA-Z0-9]) pattern is a positive character class that requires an ASCII letter of digit after any zero or more chars other than ASCII letters or digits, immediately to the right of the current location, here, from the start of string.

Upvotes: 1

Related Questions