Lets say
surname = new FormControl('', [Validators.required, Validators.minLength(2)]);
At some point depending on the situation I may add or delete any validators on surname control.
At the end How do I know what validators exists on surname control? I couldn't find any thing in documentation nor by dumping the control into console
Something like
surname.getValidators() should return - ['required', 'minLength']
Reading validators from a control is currently not supported
You can display error messages like this:
onValueChanged(data?: any) {
if (!this.heroForm) { return; }
const form = this.heroForm;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
formErrors = {
'name': '',
'power': ''
};
validationMessages = {
'name': {
'required': 'Name is required.',
'minlength': 'Name must be at least 4 characters long.',
'maxlength': 'Name cannot be more than 24 characters long.',
'forbiddenName': 'Someone named "Bob" cannot be a hero.'
},
'power': {
'required': 'Power is required.'
}
};
Refer: https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#reactive-component-template
Günter Zöchbauer's answer is still correct in Angular 6, but there is a workaround that works well for me.
My workaround depend on two observations:
First, you can see which validations are presently failing, by looking the keys on the errors object. So if you have Validators.required and Validators.minLength specified, the errors object would look like this:
{ required: true, minlenght: { ... } }
That's good enough for a lot of use cases, when you don't really care if a validator exists but doesn't prevent form submission.
Second, it turns out Angular will create validators to match the attributes set on your input. So for standard validators, my suggestion would be to not specify the validator at all.
Do something like this instead:
<input type="text" formControlName="surname" [required]="surnameRequired">
In your form declaration:
form = this.formBuilder.group({
surname: '',
anotherField: ['', Validators.required],
yetAnotherField: ['', Validators.required]
});
And then set the value of surnameRequired to add or remove the validator.
I have a working StackBlitz.
My approach doesn't work for custom validators, but the bulk of my use cases don't use those. Your mileage may vary.