admin管理员组文章数量:1429452
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..?
2 Answers
Reset to default 4You 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.
版权声明:本文标题:javascript - I want to validate words for repetitive characters in a input field using regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745502528a2661097.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论