1

Trying to validate a string of text. Rules are:

  • Must only have alpha, numeric, special (including space)
  • Cannot have more than 3 alpha characters consecutively
  • Cannot have more than 2 special characters consecutively

The validation should fail if the Regex is matched.

Separately, these work, but I've been unable to combine them correctly:

/^[^\x20-\x7F]+$/ - Regular expression to match all characters on a U.S. keyboard

/^(\w)\1{3,}$/ - Regex for detecting the same character more than five times?

Invalid Examples:

  • Thiiis would fail.
  • Thiiis wooould 222 fail 2 times.
  • !! is not allowed either.

Use case is not allowing users to dirty up postings on a marketplace (think Craigslist).

Regex engine is Javascript in an AngularJS directive.

Bonus: I would also like to let the user know what failed in the string. Currently I'm doing that for single characters, but not sure how to best output failed consecutive characters "!! is invalid":

Current Working Code Snippet:

var alphaNumeric = /^[^0-9a-zA-Z\- ]+$/;
var charArray = new Array();
for (var i = 0; i < userstring.length; i++) {
    if (alphaNumeric.test(userstring[i])) {
        charArray.push(userstring[i]);
    }
}
var errorMsg = charArray.join().toString() + " are invalid characters.";
Community
  • 1
  • 1
roadsunknown
  • 3,060
  • 6
  • 26
  • 35

1 Answers1

1

You are looking for zero-width look-ahead assertions.

(?=^[\x20-\x7F]+$)(?!^.*?(\w)\1{2,}$).*

Note the subtle changes I have made to the expressions you suggested, fixing bugs in them. The third of your requirements is trivial to add, so I leave it as an exercise for you.

To find out how this works in principle, read through my answer on this thread: Regexp Java for password validation


P.S.: Think hard whether "all characters on a U.S. keyboard" is a specification you should give any attention to, especially in the context of a web application.


Bonus: If you want to inform the user what failed in the string, you cannot do this in a single expression anymore and you must return to testing against a list of individual rules.

Community
  • 1
  • 1
Tomalak
  • 306,836
  • 62
  • 485
  • 598