Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to validate words for repetitive characters in a input field using regex

The problem is when a user enters aaaaaa or xyzzz etc. in the input field, I want to check that the user can't enter 3 similar alphabets repetitively. e.g aabb is valid, but aabbb should be invalid. I want to do it using regular expression. Is there a way to do it..?

like image 672
Ved Avatar asked Sep 19 '14 06:09

Ved


People also ask

How do you validate a regex pattern?

To validate a field with a Regex pattern, click the Must match pattern check box. Next, add the expression you want to validate against. Then add the message your users will see if the validation fails. You can save time for your users by including formatting instructions or examples in the question description.

Is regex input validation?

The Validation (Regex) property helps you define a set of validation options for a given field. In general, this field property is used to perform validation checks (format, length, etc.) on the value that the user enters in a field. If the user enters a value that does not pass these checks, it will throw an error.

What are the regular expressions and how they help in validating the inputs?

Regular Expressions are specially formatted strings for specifying patterns in text. They can be useful during information validation, to ensure that data is in a specified format. For example, a ZIP code must consist of five digits, and the last name must start with a capital letter.


2 Answers

You can use a backreference (\1) inside a negative lookahead ((?!…)) like this:

/^(?:(\w)(?!\1\1))+$/

This pattern will match any string consisting of 'word' characters (Latin letters, decimal digits, or underscores) but only if that string doesn't contain three consecutive copies of the same character.

To use the HTML5 pattern attribute, that would be:

<input type="text" pattern="^(?:(\w)(?!\1\1))+$">

Demonstration

like image 186
p.s.w.g Avatar answered Sep 19 '22 06:09

p.s.w.g


You also try this pattern with JavaScript

(\w)\1{2,}

and you can test it on jsfiddle too

The JavaScript code is like this:

jQuery(document).ready(
    function($)
    {
        $('#input').on(
            'keyup',
            function()
            {
                var $regex  = /(\w)\1{2,}/;
                var $string = $(this).val();

                if($regex.test($string))
                {
                    // Do stuff for repeated characters
                }
                else
                {
                    // Do stuff for not repeated characters
                }
            }
        );
    }
);

Where $('#input') selects the text field with ID input. Also with the {2,} in the regex pattern you can control to length if the repeated characters. If you change the 2 to 4 in example, the pattern will match 5 repeated characters or more.

like image 32
KodeFor.Me Avatar answered Sep 19 '22 06:09

KodeFor.Me