Mahesh
Mahesh

Reputation: 61

JavaScript regular expression for business name with some validation

I need JavaScript regular expression for business name with following conditions:

  1. Numbers, spaces and the following characters are allowed:

    ~ ` ? ! ^ * ¨ ; @ = $ % { } [ ] |  /. < > # “ - ‘
    
  2. Should be at least 2 characters one of which must be alpha or numeric character

  3. No preceding or trailing spaces

examples: Test1, Ta, A1, M's, 1's, s!, 1!

I tried following (for time being I used only 3 special characters for testing purpose):

^(?=(?:[^\A-Za-z0-9]*[\A-Za-z0-9]){2})[~,?,!]*\S+(?: \S+){0,}$

But it doesn't validate s! or 1!.

Upvotes: 0

Views: 7035

Answers (2)

Ehab Khallaf
Ehab Khallaf

Reputation: 1

/^(?=(?:[^\A-Za-z0-9][\A-Za-z0-9]){2})[~,?,!]\S+(?: \S+){0,}$/;

matches strings that begin with a special character, followed by a word that contains at least two non-alphanumeric characters, followed by an optional space and another word.

Upvotes: 0

karthik manchala
karthik manchala

Reputation: 13640

You can use the following to validate:

^(?!\s)(?!.*\s$)(?=.*[a-zA-Z0-9])[a-zA-Z0-9 '~?!]{2,}$

And add all the characters tht you want to allow in [a-zA-Z0-9 '~?!]

See DEMO

Explanation:

  • ^ start of the string
  • (?!\s) lookahead assertion for don't start with space
  • (?!.*\s$) lookahead assertion for don't end with space
  • (?=.*[a-zA-Z0-9]) lookahead assertion for atleast one alpha or numeric character
  • [a-zA-Z0-9 '~?!] characters we want to match (customize as required)
  • {2,} match minimum 2 and maximum any number of characters from the previously defined class
  • $ end of the string

Upvotes: 8

Related Questions