I am trying to write a RegEx for an input field in Angular / TypeScript that prevents the user from typing anything other than a 1-3 digit number not starting with 0. Restricting the input to only digits is easy, but I am not able to figure out how to restrict an input starting with 0. Everything I try seems to break the RegEx check.
<input matInput
[(ngModel)]="backupIntervalLength"
(ngModelChange)="onIntervalLengthChange($event)"
maxLength="3"
onkeypress="return String.fromCharCode(event.charCode).match(/[^0-9]/g) === null"
>
CodePudding user response:
I'm not familiar with Angular but here is a JS solution, since you didn't tag your question with Angular I assume you can translate it into Angular code.
const input = document.getElementById("input");
input.addEventListener("input", e => {
const { value } = e.currentTarget;
if (!/^[1-9]\d{0,2}$/.test(value)) {
e.currentTarget.value = value.slice(0, -1);
}
});
<input id="input" type="number" />
CodePudding user response:
Turns out it wasn't all that complicated. I just had to think in invert :)
<input matInput
[(ngModel)]="backupIntervalLength"
(ngModelChange)="onIntervalLengthChange($event)"
maxLength="3"
onkeypress="return String.fromCharCode(event.charCode).match(/[^1-9]?[^0-9]?[^0-9]/g) === null"
>