Different
The Different rule cross-checks a field against another named field on the same form and fails validation if the two values match — the opposite of the Same rule. It's the check you'd reach for when a new password must differ from the current one, a backup email address shouldn't be identical to the primary email, or a shipping address needs to be distinct from a billing address the user already entered. The 'targeted field' is simply another input on the same form, referenced by its field name, that the value is compared against.
#Directive Code Snippet
<!DOCTYPE html>
<html lang="en">
...
<form (ngSubmit)="onSubmit(form)" #form="ngForm">
<input different="name2" type="text" name="<name1>" [(ngModel)]="<name1>" #<name1>="ngModel">
<ng-absolute-validator [formInstance]="<name1>"></ng-absolute-validator>
<input type="text" name="<name2>" [(ngModel)]="<name2>" #<name2>="ngModel">
<ng-absolute-validator [formInstance]="<name2>"></ng-absolute-validator>
</form>
...
</html>
#Chain Rule Code Snippet
<!DOCTYPE html>
<html lang="en">
...
<form (ngSubmit)="onSubmit(form)" #form="ngForm">
<input rule="different:name2" type="text" name="<name1>" [(ngModel)]="<name1>" #<name1>="ngModel">
<ng-absolute-validator [formInstance]="<name1>"></ng-absolute-validator>
<input type="text" name="<name2>" [(ngModel)]="<name2>" #<name2>="ngModel">
<ng-absolute-validator [formInstance]="<name2>"></ng-absolute-validator>
</form>
...
</html>
#Reactive From 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({
<name1> : ['',this.rv.map('different:name2',<CUSTOM_MESSAGE>)],
<name2> : [''],
})
}
}
//component.html
<!DOCTYPE html>
<html lang="en">
...
<form [formGroup]="form">
<input type="text" name="<name1>" formControlName="<name1>">
<ng-absolute-validator [formInstance]="form.get(<name1>)"></ng-absolute-validator>
<input type="text" name="<name2>" formControlName="<name2>">
<ng-absolute-validator [formInstance]="form.get(<name2>)"></ng-absolute-validator>
</form>
...
</html