2

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 Answers1

1

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

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • yeah but the condition text box1=1 && text box2 =0 || text box1=0 && text box2 =1 condition should satisfy. I'm trying to achieve this condition code in stackblitz. – jhansiReddy Aug 08 '22 at 05:23
  • looking at stackblitz now – Pankaj Parkar Aug 08 '22 at 05:24
  • @jhansiReddy may I know what is `widthFt` and `widthIn`? I don't see this fields in the form – Pankaj Parkar Aug 08 '22 at 05:25
  • https://stackblitz.com/edit/angular-8-reactive-form-validation-rj2edg?file=app%2Fapp.component.ts,app%2Fapp.component.html,app%2F_helpers%2Fmust-match.validator.ts. I changed them – jhansiReddy Aug 08 '22 at 05:29
  • @jhansiReddy take a look at the updated answer – Pankaj Parkar Aug 08 '22 at 05:39
  • @PankajParkar.tqs for replying me trying to help me. but when I make changes to your code , it is not showing any error for fullName.https://stackblitz.com/edit/angular-8-reactive-form-vickr2?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html – jhansiReddy Aug 08 '22 at 05:50
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/247110/discussion-between-jhansireddy-and-pankaj-parkar). – jhansiReddy Aug 08 '22 at 06:08
  • It works, please check [here](https://stackblitz.com/edit/angular-8-reactive-form-wju5ku), there was an issue because of `invalid-feedback` CSS class, it uses `display: none` – Pankaj Parkar Aug 08 '22 at 07:25