HTML numeric input using Reactive forms is showing required validator error instead of Invalid pattern

1.9k Views Asked by At

I am working on an Angular 8 application and following reacting forms approach. Facing an issue with numeric text box and copying a sample code below.

Typescript:

this.sampleForm = this.formBuilder.group({
            age: ['', [Validators.required, Validators.pattern('/^-?(0|[1-9]\d*)?$/')]]
        });

HTML:

<div class="form-group">
                        <label>Age</label>
                        <input type="number" formControlName="age" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.age.errors }" />
                        <div *ngIf="submitted && f.age.errors" class="invalid-feedback">
                            <div *ngIf="f.age.errors.required">Age is required</div>
                             <div *ngIf="f.age.errors.pattern">invalid age value</div>
                        </div>
                    </div>

Sample Input value:

'-035040958094385-3443-4355'

Expected Validation error:

'invalid age value'

Actual validation error:

'Age is required'

3

There are 3 best solutions below

0
robert On BEST ANSWER

Your regexp should look like this: It will accept age between 1 and 200. Taken from this answer.

age: ["", [Validators.required, Validators.pattern("(0?[1-9]|[1-9][0-9]|[1][1-9][1-9]|200)")]]

Check this working stackblitz.

8
Safwan Mh On

you need to put all the Validators in array

Age: ['', [Validators.required, Validators.pattern('/^-?(0|[1-9]\d*)?$/')]]

instead of

Age: ['', Validators.required, Validators.pattern('/^-?(0|[1-9]\d*)?$/')]
1
Developer On

Check this stackblitz.. this way you can solve problem.

https://stackblitz.com/edit/angular-g9j46z?file=src%2Fapp%2Fapp.component.html