I have a very large form with a number of sections represented as separate Form Groups. At the end of each section I have a check button that checks the validity of all controls within that form group, so far it is as follows
checkValidity(g: FormGroup) {
Object.keys(g.controls).forEach(key => {
g.get(key).markAsDirty();
});
Object.keys(g.controls).forEach(key => {
g.get(key).markAsTouched();
});
}
It works fine, but because my generic validator checks and processes validation messages on each controls' input blur event, the validation messages themselves don't pop up until after I focus and blur a control. So I would like to add something to my method above that triggers a blur event on each Form control in a form group, but I haven't been able to figure out how I would do that.
document.getElementById("myAnchor").blur(); from W3Schools shows how I can get element by id and trigger it's blur() that way. Using the method above, would I be able to access all elements in a FormGroup with a forEach to trigger blur on everything? (inputs, textareas, radio buttons and checkboxes)
Please le tme know.
I just figured out a solution to this problem just now, and it didn't involve triggering blur or any DOM event. Having discovered updateValueAndValidity() for a previous problem, I called it on each control in the form group exactly the same way I marked all controls as dirty and touched in the question. Demonstrated below.
checkValidity(g: FormGroup) {
Object.keys(g.controls).forEach(key => {
g.get(key).markAsDirty();
});
Object.keys(g.controls).forEach(key => {
g.get(key).markAsTouched();
});
Object.keys(g.controls).forEach(key => {
g.get(key).updateValueAndValidity();
});
}
This properly displays the validation error messages under each control in the form group, where previously I would have to focus and then blur on any control for this to happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With