JSFiddle - React, Tailwind, and code Playground
by Michał Załęcki
HTML
<form id="signup" noValidate>
<input name="email" type="email" required>
<input name="password" minlength="8" type="password" required>
<input type="submit">
</form>
Babel + JSX
console.clear();
function Form(selector) {
this.form = document.querySelector(selector);
this.form.addEventListener("submit", ::this.handleSubmit);
}
Form.prototype.handleSubmit = function (e) {
e.preventDefault();
}
Form.prototype.isValid = function () {
return this.form.checkValidity();
}
Form.prototype.gatherData = function (e) {
return Array.from(this.form.elements)
.filter(({ name }) => name)
.reduce((akk, input) =>
({...akk, [input.name]: input.value}), {});
}
Form.prototype.gatherErrors = function (e) {
return Array.from(this.form.elements)
.filter(input => input.name && input.validationMessage)
.reduce((akk, input) =>
({...akk, [input.name]: input.validationMessage}), {});
}
function SignupForm(...args) {
Form.apply(this, args);
}
SignupForm.prototype = Object.create(Form.prototype);
SignupForm.prototype.constructor = SignupForm;
SignupForm.prototype.handleSubmit = function (e) {
Form.prototype.handleSubmit.call(this, e);
if (this.isValid()) {
console.log(this.gatherData());
} else {
console.warn(this.gatherErrors())
}
}
new SignupForm("#signup");