Reputation: 31
let productIdPattern = /[0-9]{3}[A-Z]{3}[0-9]{3}/
let userInput = '123A'
if (userInput.match(productIdPattern)) {
alert("'123A' is ok, go ahead typing!")
}
Given is the above JavaScript pseudo code.
A User is typing a Product-ID. For every keystroke I want to check if the input will match the Product-ID pattern. If not, the keystroke will be ignored. So the input must follow the pattern.
For example:
Is there a way to achieve this without making many different or complex patterns for each input length? I need a way to tell the "String.match()" function to ignore the rest of the pattern, if the string is shorter than the pattern.
Upvotes: 3
Views: 182
Reputation: 18950
We can create an input filter that only allows entering the desired pattern; everything else is immediately dropped. This is achieved using an in-place replacement pattern:
<input type="text" formControlName="productIdInputC"
onkeyup="this.value = this.value.replace(/^([0-9]{3}[A-Z]{3}[0-9]{1,3}|[0-9]{3}[A-Z]{1,3}|[0-9]{1,3})?.*$/, '$1')">
Though, you should still have server-side validation.
Upvotes: 1