javascript - I want to validate words for repetitive characters in a input field using regex - Stack Overflow

The problem is when a user enters aaaaaa or xyzzz etc. in the input field, Iwant to check that the us

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..?

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..?

Share Improve this question edited Sep 25, 2014 at 7:08 Ved asked Sep 19, 2014 at 6:01 VedVed 12.1k5 gold badges45 silver badges61 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745502528a4630481.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信