This might be similar to Formik but in a hook form , and this is also use json-msg as a validator. Json-msg is a lightweight alternative for yup and joi or any other schema validator.
- Basic knowledge of json-msg for building schema
Check json-msg documentation here
npm install json-msg-react
or
yarn add json-msg-react
import React from "react";
import jm, { useForm } from "json-msg-react";
const schema = {
username: jm.str({ min: 5 }),
password: jm.str({ min: 8, max: 40 }),
pin: jm.num({ digit: 4 }),
};
const initialData = {
username: "",
password: "",
pin: 0,
};
const Example = () => {
const { handleChange, handleSubmit, errors } = useForm(initialData, schema);
function submit(data) {
console.log(data);
}
return (
<>
<form onSubmit={handleSubmit(submit)}>
<input name="username" onChange={handleChange} />
{errors.username && <p> {errors.username} </p>}
<input name="password" type="password" onChange={handleChange} />
{errors.username && <p> {errors.username} </p>}
<input name="pin" type="number" onChange={handleChange} />
{errors.password && <p> {errors.password} </p>}
</form>
</>
);
};
- initialData:? Object
- schema:? Object
option | type | default | description |
---|---|---|---|
showAllErrors | boolean | false | Show all the errors in array form |
trim | boolean | false | Trim all the string in the data |
validateOnChange | boolean | true | Validate on change the data |
validateOnMount | boolean | false | Validate the data on mount |