Reputation: 79
I am trying to validate text input in JavaScript to prevent 2 consecutive numbers. ex:
name2aaa accept
name22aa not accept
I am using the validation on text input. And that's my code, it's already contains prevent @ sign, I want to add the prevent 2 consecutive numbers rule to the same regex
$('#storename').on('input', function () {
var c = this.selectionStart,
r = /[\\\@@]/g,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
Upvotes: 0
Views: 418
Reputation: 20669
This is probably what you need:
[\\@]|(\d)\d+
[\\@]
: \
or @
|
: or(\d)\d+
: a digit with 1 or more digits ahead, put the first digit in group 1$1
Assuming you don't want user to type another digit if there's already a digit before it.
When user tries to type 42
, it stores 4
in the group, and replace all the digits with that group. In this case, 42
-> 4
. So users can no longer type more than 1 digit in a row.
$('#storename').on('input', function () {
var c = this.selectionStart,
r = /[\\@]|(\d)\d+/g,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, '$1'));
c--;
}
this.setSelectionRange(c, c);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="storename" />
Upvotes: 1