I am trying to implement a custom validator using clarity design which compares two form control values and returns true if first form control value is greater than the second. How do i do it ?
The example posted was close to working, but a few things need to change to get this to work. Make sure on your group validation function that the error message returns matches the same error message defined in the template. In my example the error message is passwordMissmatch
.
Since this is a group validator the clr-control-error
will not pick up the group error messages (that I know of), it only displays individual control errors. To display the group error listen to the errors on the root form group.
<form clrForm [formGroup]="form" (ngSubmit)="submit()">
<clr-password-container>
<label>Password</label>
<input clrPassword formControlName="password" />
<clr-control-error>Password Required</clr-control-error>
</clr-password-container>
<clr-password-container>
<label>Confirm Password</label>
<input clrPassword formControlName="confirmPassword" />
</clr-password-container>
<clr-alert *ngIf="form.errors?.passwordMissmatch && form.controls.confirmPassword.touched" clrAlertType="danger" [clrAlertClosable]="false">
Passwords must match.
</clr-alert>
<button class="btn btn-primary">Submit</button>
</form>
form: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
password: ['', [Validators.required]],
confirmPassword: ['']
}, { validators: this.checkPasswords });
}
checkPasswords(group: FormGroup) {
return group.controls.password.value === group.controls.confirmPassword.value ? null : { passwordMissmatch: true };
}
Here is the fully working stackblitz https://stackblitz.com/edit/clarity-oshxxw
You can also create a more reusable generic group validator that can compare any two inputs by passing in the control name. Example:
...
new FormGroup({
password: new FormControl('', [Validators.required, Validators.minLength(6)]),
confirm: new FormControl('', Validators.required)
}, matchingInputsValidator('password', 'confirm', 'missmatch'))
...
export function matchingInputsValidator(firstKey: string, secondKey: string, errorName: string) {
return function (group: FormGroup): ValidationErrors | undefined {
if (group.controls[firstKey].value !== group.controls[secondKey].value) {
return {
[errorName]: true
};
}
};
}
You can find a more detailed explanation here: https://coryrylan.com/blog/build-accessible-forms-with-angular