Forked from JohannesHoppe/get-form-validation-errors.ts
Last active
October 11, 2023 14:13
-
-
Save krohne/64d3b1e2d5430fb291cec2592a0843e8 to your computer and use it in GitHub Desktop.
Get all validation errors for Angular FormGroup, FormRecord, or FormArray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
FormGroup, | |
FormRecord, | |
FormArray, | |
ValidationErrors | |
} from '@angular/forms'; | |
export function getFormValidationErrors(form: FormGroup|FormRecord|FormArray, path ?: string = '$') { | |
const result = []; | |
const formErrors: (ValidationErrors|null|undefined) = form.errors; | |
if (formErrors) { | |
Object.entries(formErrors).forEach( ([keyError, message]) => { | |
result.push({ | |
'control': 'form', | |
'error': keyError, | |
'value': message, | |
'path': path | |
}); | |
}); | |
} | |
if (form instanceof FormArray) { | |
form.controls.forEach( ([control, index]) => { | |
if (control instanceof FormGroup || control instanceof FormRecord || control instanceof FormArray) { | |
result.push(...getFormValidationErrors(control, `${path}.[${index}]`)) | |
} else { | |
const controlErrors: (ValidationErrors|null|undefined) = control.errors; | |
if (controlErrors) { | |
Object.entries(controlErrors).forEach( ([keyError, message]) => { | |
result.push({ | |
'control': key, | |
'error': keyError, | |
'value': message, | |
'path': `${path}.[${index}].${key}` | |
}); | |
}); | |
} | |
} | |
}); | |
} else { | |
Object.entries(form.controls).forEach( ([key, control]) => { | |
if (control instanceof FormGroup || control instanceof FormRecord || control instanceof FormArray) { | |
result.push(...getFormValidationErrors(control, `${path}.${key}`)) | |
} else { | |
const controlErrors: (ValidationErrors|null|undefined) = control.errors; | |
if (controlErrors) { | |
Object.entries(controlErrors).forEach( ([keyError, message]) => { | |
result.push({ | |
'control': key, | |
'error': keyError, | |
'value': message, | |
'path': `${path}.${key}` | |
}); | |
}); | |
} | |
} | |
}); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added JSONPath
path
, in case the recursion gets deep.