I want to check words for duplicate characters in an input field using regex

The problem is that the user enters aaaaaa or xyzzz , etc. in the input box, I want to check that the user cannot re-enter 3 identical alphabets. for example, aabb is valid, but aabbb must be invalid. I want to do this using regex. Is there any way to do this ??

+5
source share
2 answers

You can use the backlink ( \1 ) inside the negative view ( (?!…) ) as follows:

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

This pattern will match any string consisting of word characters (latin letters, decimal digits, or underscores), but only if this string does not contain three consecutive copies of the same character.

To use the HTML5 pattern attribute, this would be:

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

Demonstration

+3
source

You can also try this template using JavaScript.

 (\w)\1{2,} 

and you can check it on jsfiddle too

JavaScript code is as follows:

 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 a text field with input identifier. Also with {2,} in the regex pattern you can control the length if duplicate characters. If you change Example 2 to 4 , the pattern will match 5 repeated characters or more.

+2
source

Source: https://habr.com/ru/post/1202940/


All Articles