Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import "./styles.css";
import type { FormEvent } from "react";
function getFormValues(formElement: HTMLFormElement) {
return Object.fromEntries(new FormData(formElement).entries());
}
function Form({ validator = {}, handleSubmit, children }) {
function handleBlurs(e: FormEvent<HTMLFormElement>) {
const formElement = e.currentTarget;
const inputElement = e.target;
const formValues = getFormValues(formElement);
for (let [inputName, validator] of Object.entries(validator)) {
formElement.elements[inputName].setCustomValidity(
validator(formValues[inputName]) ?? ""
);
}
const inputNames = Object.values(formElement.elements)
.filter((el) => el.getAttribute("name"))
.map((el) => el.getAttribute("name"));
formElement.elements[inputElement.getAttribute("name")].reportValidity();
// for (const inputName of inputNames) {
// formElement.elements[inputName].reportValidity();
// }
const submitElement = formElement.querySelector('input[type="submit"]');
if (submitElement) {
const isValid = inputNames.some((inputName) =>
formElement.elements[inputName].checkValidity()
);
submitElement.disabled = isValid === false;
}
}
function onSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
handleSubmit(getFormValues(e.currentTarget));
}
return (
<form onSubmit={handleSubmit} onBlurCapture={handleBlurs}>
{children}
</form>
);
}
export default function App() {
function handleSubmit(formData) {
console.log(formData);
}
const validator = {
name: (value: string) =>
value !== "Seb" ? "Wow, very specific validator!" : "",
country: (value: string) =>
value !== "United States" || value !== "United Kingdom"
? "Please enter either United States or United Kingdom"
: ""
};
return (
<Form validator={validator} onSubmit={handleSubmit}>
<fieldset>
<legend>testing</legend>
<div>
<label htmlFor="name">Name</label>
<input id="name" type="text" name="name" />
</div>
<div>
<label htmlFor="country">Country</label>
<input id="country" type="text" name="country" />
</div>
<input type="submit" disabled />
</fieldset>
</Form>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment