function setValidatorNumber(id, regex) {
var element = document.getElementById(id);
if (element) {
var lastValue = element.value;
if (!regex.test(lastValue))
lastValue = '';
setInterval(function() {
var value = element.value;
if (value != lastValue) {
if (regex.test(value))
lastValue = value;
else
element.value = lastValue;
}
}, 10);
}
}
setValidatorNumber('number', /^[0-9]{0,4}$/);
<body>
<form role="form">
<div class="form-group " id="box">
<label class="control-label" id="label" for="input"></label>
<input type="text" class="form-control" id="input">
</div>
</form>
</body>
const input = document.getElementById('input');
const box = document.getElementById('box');
const label = document.getElementById('label');
const re = /^[0-9]{0,4}$/;
input.addEventListener('input', validate);
function validate(e) {
const value = e.target.value.trim();
console.log(value);
if(!value) {
label.textContent = '';
box.className = "form-group";
return;
}
if(re.test(value)) {
box.className = "form-group has-success";
label.textContent = "Well, it's ok for now!";
} else {
box.className = "form-group has-warning";
label.textContent = "Oh dude, totally weak!";
}
}