user14485875
user14485875

Reputation: 31

Javascript Regex - Match string shorter than expression?

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

Answers (2)

wp78de
wp78de

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

Donut
Donut

Reputation: 112795

Try this pattern instead:

/^(?:\d{1,3}|\d{3}[A-Z]{1,3}|\d{3}[A-Z]{3}\d{1,3})$/

You can see a visualization of how this works here.

Upvotes: 0

Related Questions