I am struggling with a Regex for this format [40]*100 where the user can enter up to 3 digits inside the square brackets and up to 3 next to the multiplication sign. The plus sign can only appear if the previous format of [40]*100 is respected (the plus is optional at the end). And if they extend the input they should be able to extend that format like this [40]*100 [20]*100 [40]*100 and so on.
This determines if the input is valid but trying to control the format escapes me.
function isValid2(str) {
return !/[~`!@#$%\^a-zA-Z&()=\-\\\';,/{}\\":<>\?]/g.test(str);
}
$('input.cut_text').on('input change keydown', function () {
if (isValid2(this.value) == false){
this.value = this.value.replace(/[^1-9]/g,'');
return false
}
});
CodePudding user response:
This regexp tests for the format you describe:
/^(\[\d{1,3}\]\*\d{1,3}\ ) $/
\d{1,3}
matches up to 3 digits. We put one of these inside literal []
, with literal *
after that, and literal
after the second one. Then we use a quantified group to allow multiple repetitions.
You can't do the validation until the user has finished entering the field, because it won't match the partial value while they're typing. So you can use it in a change
event listener, but not input
or keydown
.