Reputation: 10850
I have an ng2 form with the following control:
<input class="form-field"
type="text"
id="fieldName"
name="fieldName"
#fieldName="ngModel"
(ngModelChange)="onFieldNameChange($event)"
[(ngModel)]="model.fieldName"
[ngModelOptions]="{updateOn: 'blur'}"
suCustomValidator="message"
[suAnotherCustomValidator]="booleanConditionInComponentTs">
(where su is the prefix for my custom components)
As part of a template form.
At what point are the validators and custom validators triggered? How can I force this field to be validated on the change of another field an on the touch of this field?
Upvotes: 0
Views: 420
Reputation: 8178
Since not clear about your requirement, Except for the fact that you need to have a local custom validator for each field and global validator for fields to have mutual impacts.
A good example good be password
and repeat password
fields
private buildForm(): void {
this.form = this.fb.group({
password: [null, Validators.required], // define password field to be mandatory (can have custom validator func call too)
repeat: [null, Validators.required]// define repeat password field to be mandatory (can have custom validator func call too)
}, {validator: this.matchingPasswords('password', 'repeat')}); // have global validator to check when inputs are mades
}
private matchingPasswords(password: string, repeat: string) {
return (group: FormGroup) => {
const passwordIn = group.controls[password];
const repeatIn = group.controls[repeat];
if (passwordIn.value !== repeatIn.value) {
return repeatIn.setErrors({notEquivalent: true});
} else {
return repeatIn.setErrors(null);
}
};
}
In html templates
<p *ngIf="form.get('repeat')?.errors?.notEquivalent">Passwords did not match</p>
<p *ngIf="form.get('repeat')?.errors?.required">Confirm password is required</p>
<p *ngIf="form.get('password')?.errors?.required">Password is required</p>
Few Useful links:
Trigger validations on submit of forms
Custom validation using multiform fields
Upvotes: 1