55SK55
55SK55

Reputation: 691

Avoid leading and trailing spaces on Alphanumeric string

I'm trying to validate the string to have only the followings

1.  Numbers (0-9) are valid
2.  Letters (A-Z, a-z) are valid
3.  No leading spaces are allowed
4.  No trailing spaces are allowed
5.  A space can be entered in the field text (outside of leading or trailing spaces)
6.  The following special characters are allowed:
    1.  Underscore (_)
    2.  Hyphen (-)
    3.  Comma (,)
    4.  Dot (.)

The following is working for me, except spaces

/^[A-Za-z0-9][A-Za-z0-9\_\.\-\,\s]*$/g

How to avoid leading spaces and trailing spaces with same Regex pattern?

Upvotes: 2

Views: 3343

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18611

The leading spaces can be forbidden with (?!\s) lookahead.

The trailing spaces can be forbidden with (?!.*\s$) lookahead.

Combine them into your pattern after ^:

/^(?!\s)(?!.*\s$)[A-Za-z0-9][A-Za-z0-9\_\.\-\,\s]*$/

See proof

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163207

If there can be consecutive whitespaces characters in between, you could use an optional part where there second character class is repeated 0+ times ending with the same character class excluding \s

^[A-Za-z0-9](?:[A-Za-z0-9_.,\s-]*[A-Za-z0-9_.,-])?$

Regex demo

Or using \w to match word characters:

^[A-Za-z0-9](?:[\w.,\s-]*[\w.,-])?$

Note that \s could also possibly match a newline.

Upvotes: 4

Related Questions