RequiredWithout
The Required Without rule makes a field mandatory only when at least one of a set of other named fields is missing — required_without:requiredWithout_1,requiredWithout_2 means the current field must be filled in if either requiredWithout_1 or requiredWithout_2 is absent. It's the natural fit for 'provide this or that' scenarios, like requiring a 'phone number' field whenever an 'email address' field hasn't been supplied, so the user always leaves at least one contact method behind. As with the other conditional-required rules, every field being watched needs to be defined or initialized before the field that depends on it.
#Directive Code Snippet
<!DOCTYPE html>
<html lang="en">
...
<form (ngSubmit)="onSubmit(form)" #form="ngForm">
<input requiredWithout="<TARGET_FIELDS>" type="text" name="<name>" [(ngModel)]="<name>" #<name>="ngModel">
<ng-absolute-validator [formInstance]="<name>"></ng-absolute-validator>
</form>
...
</html>
#Chain Rule Code Snippet
<!DOCTYPE html>
<html lang="en">
...
<form (ngSubmit)="onSubmit(form)" #form="ngForm">
<input rule="required_without:<TARGET_FIELDS>" type="text" name="<name>" [(ngModel)]="<name>" #<name>="ngModel">
<ng-absolute-validator [formInstance]="<name>"></ng-absolute-validator>
</form>
...
</html>
#Reactive Form Code Snippet
//component.ts
export class ReactiveComponent{
public form !: FormGroup;
constructor(
private fb : FormBuilder,
private rv : ReactiveValidator,
){this.generteForm()}
generteForm(){
this.form = this.fb.group({
<name> : ['',this.rv.map('required_without:<TARGET_FIELDS>',<CUSTOM_MESSAGE>)]
})
}
}
//component.html
<!DOCTYPE html>
<html lang="en">
...
<form [formGroup]="form">
<input type="text" name="<name>" formControlName="<name>">
<ng-absolute-validator [formInstance]="form.get(<name>)"></ng-absolute-validator>
</form>
...
</html>