Is there a way to make form fields required or not based on the value of other fields? The standard RequiredValidator directive doesn't seem to support this, so I've created my own directive:
@Directive({
selector: '[myRequired][ngControl]',
providers: [new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MyRequiredValidator), multi: true })]
})
class MyRequiredValidator {
@Input('myRequired') required: boolean;
validate(control: AbstractControl): { [key: string]: any } {
return this.required && !control.value
? { myRequired: true }
: null;
}
}
Here's an example of how to use it:
<form>
<p><label><input type="checkbox" [(ngModel)]="isNameRequired"> Is Name Required?</label></p>
<p><label>Name: <input type="text" [myRequired]="isNameRequired" #nameControl="ngForm" ngControl="name" [(ngModel)]="name"></label></p>
<p *ngIf="nameControl.control?.hasError('myRequired')">This field is required.</p>
</form>
While this works when toggling between checkboxes and text boxes with input, there seems to be an issue when changing the checkbox while the text box is empty. How can I update MyRequiredValidator
to trigger validation when the required
property changes?
Please note that I'm only looking for modifications to MyRequiredValidator
, and prefer not to add logic to the App component.
Check out the Plunker here: https://plnkr.co/edit/ExBdzh6nVHrcm51rQ5Fi?p=preview