How to custom validate two text boxes with a regular expression /^[1-9]\d*$/?

Viewed 51
1 Answers

You can add that in textbox1 and textBox2 controls validators

this.registerForm = this.formBuilder.group(
  {
    textbox1: ['', [Validators.required, Validators.pattern("^[1-9]\d*$/"]],
    textbox2: ['', [Validators.required, Validators.pattern("^[1-9]\d*$/"]],
  }
];

Now remove the validator from the formGroup, Validators.pattern will make sure to apply validation on both the field.

Now add errors.pattern inside *ngIf condition to see whether that pattern matched or not.

<div *ngIf="f.textbox1.errors.pattern">should not start with 0</div>
...
<div *ngIf="f.textbox2.errors.pattern">should not start with 0</div>

Updated Stackblitz

Related