I am using reactive forms with my angular. I would like to know if my form thrown any required
error in any of the form field.
at present I am finding by :
this.transtForm.get('Name').hasError('required')
- But there in 20 form fields are exist in the page. so I would like to know minimum any one of the field has the required
error with true state.
I can't use the this.transtForm.valid
- because user may even typed wrong email ids too.. that's allowed. it will taken care by email pattern on focus out.
This may help, something like this? We hold 20 fields in an array as below and one function will go through the array and throw an alert if there any errors.
const fields = [
{ label: 'Name', validations: ['required'] },
{ label: 'Email', validations: ['required', /\w+/g] }
];
function isValidForm() {
for (const field of fields) {
field.validations.map(validator => {
if (typeof validator === 'string') {
if (this.transtForm.get(field.label).hasError(validator)) {
alert('Your error message');
}
} else {
if (!validator.test('')) {
alert('Your error message');
}
}
});
}
}
if (isValidForm()) {
// Do stuff here...
}