Skip to content

Instantly share code, notes, and snippets.

@everdimension
Created July 31, 2019 16:49
Show Gist options
  • Save everdimension/589fc3eb029a4e9858552af09580e7e8 to your computer and use it in GitHub Desktop.
Save everdimension/589fc3eb029a4e9858552af09580e7e8 to your computer and use it in GitHub Desktop.
Collect all errors of an html form. The "errors" object can be serialized.
/**
* Considering that each html input
* has a "name" attribute and proper
* validation attributes (type, pattern, required, etc)
* we collect "validity" states of invalid inputs
* and the "validationMessage" provided by the browsers
*/
const errors = Array.from(form.elements)
.filter((el) => el.hasAttribute('name'))
.reduce((acc, el) => {
const field = el.validity ? el : el[0];
if (!field.validity.valid) {
acc[field.name] = {
validity: field.validity,
validationMessage: field.validationMessage
};
}
return acc;
}, {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment