if (!this.formValid()) {
const error: AllValidationErrors = getFormValidationErrors(this.regForm.controls).shift();
if (error) {
let text;
switch (error.error_name) {
case 'required': text = `${error.control_name} is required!`; break;
case 'pattern': text = `${error.control_name} has wrong pattern!`; break;
case 'email': text = `${error.control_name} has wrong email format!`; break;
case 'minlength': text = `${error.control_name} has wrong length! Required length: ${error.error_value.requiredLength}`; break;
case 'areEqual': text = `${error.control_name} must be equal!`; break;
default: text = `${error.control_name}: ${error.error_name}: ${error.error_value}`;
}
this.error = text;
}
return;
}
this.form = new FormGroup({
firstName: new FormControl('', [Validators.required, validateName]),
lastName: new FormControl('', [Validators.required, validateName]),
email: new FormControl('', [Validators.required, validateEmail]),
dob: new FormControl('', [Validators.required, validateDate])
});
private isFormGroup(control: AbstractControl): control is FormGroup {
return !!(<FormGroup>control).controls;
}
// Returns a tree of any errors in control and children of control
allErrors(control: AbstractControl): any {
if (this.isFormGroup(control)) {
const childErrors = _.mapValues(control.controls, (childControl) => {
return this.allErrors(childControl);
});
const pruned = _.omitBy(childErrors, _.isEmpty);
return _.isEmpty(pruned) ? null : pruned;
} else {
return control.errors;
}
}
**I met the same problem and for finding all validation errors and
displaying only first error, I wrote next method:**
> first declare variable on top
public errors: any = [];
public fieldError: any = '';
> now subscribe form on noOnInit
this.form.valueChanges.subscribe(() => {
this.showOnlyFirstError(this.form);
this.errors = []
});
this.showOnlyFirstError(this.form);
> now call function
showOnlyFirstError(form) {
Object.keys(form.controls).forEach(key => {
const controlErrors: ValidationErrors = form.get(key).errors;
if (controlErrors != null) {
Object.keys(controlErrors).forEach(keyError => {
const showMessage = key + " is " + keyError
this.errors.push(showMessage)
this.fieldError = this.errors[0]
});
}
});
}