Reputation: 37
How to Set Custom Validation Angular as i am getting undefined of controls
FormControl.setValidators(this.validateCall);
validateCall(): ValidatorFn {
return (control: FormControl): ValidationErrors | null => { // not getting control value here
const val = control.value;
if(val == null || val == undefined) {
return {
atLeastOneRequired: {
valid: false
}
}
}
return null;
}
Upvotes: 2
Views: 4163
Reputation: 73337
Your custom validator seems incorrect. You should remove
return (control: FormControl): ValidationErrors | null => {
Also no need for the nested object in the error. So modify your validator to:
validateCall(ctrl: AbstractControl): ValidationErrors | null {
const val = ctrl.value;
if (!val || val === '') {
return {
atLeastOneRequired: true
}
}
return null;
}
The way you are setting the validator to the formcontrol is correct, since according to your comment i did it here for common understanding actually I am using this on formControl not on the class. In some cases you might also need to manually call updateValueAndValidity
on the form control after setting the custom validator.
Upvotes: 2
Reputation: 888
Reactive forms validation. form-validation
this.heroForm = new FormGroup({
'name': new FormControl(this.hero.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
]),
'alterEgo': new FormControl(this.hero.alterEgo),
'power': new FormControl(this.hero.power, Validators.required)
});
Upvotes: 0