Reputation: 1912
I have a form here
<form action="/customer" method="post" id="customer-summary">
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" >
<input type="submit" value="submit">
</form>
and here what I want is to prevent the form submit when users enter the same 4 numbers in row. Right now its preventing users to submit when they enter same 2 numbers but not in the row.
jsFiddle: https://jsfiddle.net/m31h1zhg/
var inputNode = document.getElementById('my_account');
var customer_summary = document.getElementById('customer-summary');
customer_summary.addEventListener('submit', function(e) {
console.log(is_unique(inputNode.value));
if (!is_unique(inputNode.value)) {
e.preventDefault();
alert("prevent submit");
}
});
function is_unique(val) {
for(var i = 0; i < val.length; i++) {
if (val.indexOf(val.charAt(i)) != val.lastIndexOf(val.charAt(i))) {
return false;
}
}
return true;
}
Right now I have 123145678
(same 2 numbers not in a row) which is what I don't want. I want the same 4 numbers in row be prevented, for example 111123412
How could I do this?
Upvotes: 0
Views: 45
Reputation: 3817
You can validate the input with some regex like so
if(/\d*(\d)\1{3,}\d*/.test(value)){
....
}
https://jsfiddle.net/am1wabgf/
The regex looks for a digit thats being repeated 4 or more times and if so the test returns true in Javascript.
Also I changed the input type to 'number' instead of text so it automatically throws an error if the user enters any letters.
Upvotes: 1