I need a from validation for only matching integers. Therefore I use the patternvalidator with regex (see below). Additionally the field should not be empty, so I added the required validator.
But the pattern error is never triggered. i read the angular docs and had a look to the source code of pattern and it still makes no sense to me. Additionally, I have read nearly every question on stackoverflow related to this topic. But I still can't figure out why the pattern is not working.
Maybe some of you guys might be able help me, thank you!
Here is my code component.ts:
// definition of the formcontrol
hours = new FormControl('', [
  Validators.required,
  Validators.pattern('^[0-9]*$'),
])
// for debugging
log() {
  console.log('required: ', this.hours.hasError('required'));
  console.log('pattern: ', this.hours.hasError('pattern'));
  console.log('Erros: ', this.hours.errors);
}
template:
<mat-form-field>
  <input matInput [formControl]="hours" (input)="log()"
    placeholder="Anzahl der ausbezahlten Überstunden" type="number">
  <mat-error *ngIf="hours.hasError('required') && !hours.hasError('pattern')">
    Anzahl der Überstunden fehlt!
  </mat-error>
  <mat-error *ngIf="!hours.hasError('required') && hours.hasError('pattern')">
    Anzahl muss eine Ganzzahl sein!
  </mat-error>
</mat-form-field>
Examples inputValue="":
required: true
pattern: false
Error: Object { required: true }
inputValue="1":
required:  false
pattern:  false
Error:  null
inputValue="a":
required:  true
pattern:  false
Error: Object { required: true }
                it doesn't work with type="number",if you change it to type="text" it will work
try this way, normaly I use formBuilder here
component
 this.form = fb.group({
    age:[null , [Validators.required , Validators.pattern('[0-9]*')]]
  })
template
<ng-container *ngIf="form.get('age').invalid && (form.get('age').touched || form.get('age').dirty)">
  <div *ngIf="form.get('age').hasError('required')">
    Required...
  </div>
  <div *ngIf="form.get('age').hasError('pattern')">
    Pattern Not valid
  </div>
</ng-container>
stackblitz demo 🚀🚀
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With