0

in order to validate a simple PIN, which can include leading 0, I wrote the following very-simple regexp:

^[0-9][0-9][0-9][0-9][0-9][0-9]$

This one works as expected on the different online regexp tools I tried, however, it doesn't work in Angular validator, because of the leading 0 which is not counted as a digit:

  PIN = new FormControl('', [
    Validators.required,
    Validators.minLength(6),
    Validators.maxLength(6),
    Validators.pattern('^([0-9][0-9][0-9][0-9][0-9][0-9])$'),
  ]);

  formPINGroup = this.formBuilder.group({
    PIN: this.PIN,
  });

I can't figure this out despite the different forums I browsed, people are always looking for the opposite.

If an Angular expert sees this post, his help is welcomed!

In the meantime, take care!

EDIT:

I have created a Stackblitz if you wanna try something: https://stackblitz.com/edit/angular-zzsjn1

here three results:

  • the first is not OK because of the leading 0
  • second is ok because I added number 6, at the end
  • the last one is wrong, obviously.

enter image description here

Sébastien
  • 103
  • 1
  • 11

1 Answers1

0

The problem is an HTML5 input element. Try changing type="number" to type="tel" in hello-component.ts (from your link). With it you can technically still enter some non-numeric characters but only your pattern of 6 digits (with or without leading zeroes) will validate. See also this thread

Zwiers
  • 3,040
  • 2
  • 12
  • 18