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

82 views Asked by At

I'm trying to write a custom validator for 2 text boxes, with some conditions.

Please see the code I wrote in Stackblitz Link to validate the text boxes with some conditions

Kindly help me where did I go wrong.

1

There are 1 answers

8
Pankaj Parkar On

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