2

I need a Regular expression to validate string for below rules.

  1. String should not contain any repeated characters more than 2 times.
  2. String should not allow special characters like &, <, %

So far I managed to create regular expression

/(?!(.)\1{2,})^([a-zA-Z0-9''\.\-\,]+\s?)*$/i

which validates rules 1 & 2. But only problem what I have is it only validates rule at the start of string.

1
  • Any feedback on the two answers you received? Commented Sep 27, 2016 at 8:04

2 Answers 2

2

Change your regex to

/(?!.*(.)\1{2,})^([a-zA-Z0-9'".,-]+\s?)*$/i
    ^^

It will allow the negative lookahead to work on the whole regex instead of the beginning.

See demo

Sign up to request clarification or add additional context in comments.

2 Comments

Why isn't [a-zA-Z0-9] [\w]?
@HappyCoding because \w also include the _
2

For your negative lookahead to work, you have to make it so it could match a 3-in-a-row at any place in the validated string ; just add a .* at its start :

/(?!.*(.)\1{2,})^([a-zA-Z0-9'".\-,]+\s?)*$/i

I also changed your two consecutive single-quotes in your character class to the single-quote and double quote I assume you want to allow and removed unnecessary backslashes escapes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.