Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2+ custom validator "required if" another field is filled in

I'm trying to create a custom validator for a template driven form where if one field is filled in another becomes required, but if the first field is empty the second isn't needed either.

Following the (typescript) examples in the docs to build a custom validator directive I can get that running on a field, and pass it the name of another one. Now here are my questions...

If a value is entered in field one and I check that field 2 is empty, how do I set "invalid" on field 2? (I realize I have access to its AbstractControl).

If I've set "invalid" on field 2 myself, do I need a separate validator on field 2 to remove its invalid status when it's filled in?

Or should I add the built in "required" validator on field 2 when the validator for field one is triggered (and if so how)?

Many thanks for any pointers!

like image 651
steverippl Avatar asked Sep 19 '17 22:09

steverippl


1 Answers

I think you can achieve what you are after without a custom validator.

The code below is from a template driven form - binding the required validator directive on the second field to the ngModel value from the first field. So here you've got conditional validation applied to the second field, when the first field has a value.

First: <input type="text" name="first" [(ngModel)]="theFirst" #first="ngModel" >

Second: <input type="text" ngModel [required]="theFirst ? true : null " #second="ngModel" name="second"/>

<div *ngIf="second.errors">
  <span [hidden]="!second.errors.required">Second is required</span>
</div>

Further discussion on conditional validation bindings is here.

like image 77
Garth Mason Avatar answered Sep 30 '22 17:09

Garth Mason