Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7: Formvalidation, Validators.pattern not working

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 }
like image 523
Max Avatar asked Feb 26 '19 08:02

Max


2 Answers

it doesn't work with type="number",if you change it to type="text" it will work

like image 173
onik Avatar answered Sep 17 '22 13:09

onik


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 🚀🚀

like image 39
Muhammed Albarmavi Avatar answered Sep 17 '22 13:09

Muhammed Albarmavi