4

I have this ^[a-zA-Z0-9 @&$]*$, but not working for me in few cases.

If someone types

  • A string that only consists of digits (e.g. 1234567)
  • A string starting with a special character (e.g. &123abc)

need to be rejected. Note that a special char can be in the middle and at the end.

2
  • 2
    Could you list exactly what conditions need to be rejected and why? Commented Aug 16, 2017 at 19:02
  • Should the pattern accept empty string? If not also try /^\b(?=\d*\D)[a-z\d @&$]+$/i. It's not very clear (this pattern requires at least one character). Commented Aug 16, 2017 at 19:40

2 Answers 2

8

You seem to need to avoid matching strings that only consist of digits and make sure the strings start with an alphanumeric. I assume you also need to be able to match empty strings (the original regex matches empty strings).

That is why I suggest

^(?!\d+$)(?:[a-zA-Z0-9][a-zA-Z0-9 @&$]*)?$ 

See the regex demo

Details

  • ^ - start of string
  • (?!\d+$) - the negative lookahead that fails the match if a string is numeric only
  • (?:[a-zA-Z0-9][a-zA-Z0-9 @&$]*)? - an optional sequence of:
    • [a-zA-Z0-9] - a digit or a letter
    • [a-zA-Z0-9 @&$]* - 0+ digits, letters, spaces, @, & or $ chars
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

6 Comments

If i want to exclude some and include some special character, how i can exclude some, for inclusion, i see it from your regex.
@Sharpeye500: Sorry, what do you mean? If you do not want to match a char, do not add it to the character class in the first place.
If have a "." (period) in between characters, currently the regex accepts it. For example, "Test.Work", if i need that to be rejected "." , how do i exclude in the regex.
@Sharpeye500: Not sure what you mean,
If i type a word say, "Sharpeye500@" it is valid and correct, if i type "Sharpe.Eye500", with a dot in it, it is supposed to be invalid, however with that regex, it says valid, i want to say it as invalid when there is a dot in the word.
|
1

you can do it with the following regex

^(?!\d+$)\w+\S+ 

check the demo here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.