Validation
To enable validation, pass your validator functions to validators object and map them
to your form keys defined with the initial object.
Provide the onSubmitForm function which doesn't get called unless all fields passed validation, so this simple setup guards
against invalid requests being sent to your server.
Returning a Promise in onSubmitForm function sets isSubmitting value to true until promise resolves.
Use the supplied submit method to trigger the validation -> onSubmitForm process.
By default, the fields are validated sequentially.
validations object contains validation information for each of your form fields.
Use error, validating and checked properties to update the UI.
import { useForm } from "@formeus/react"
function SignIn() {
const { values, update, submit, validations, isSubmitting } = useForm({
initial: {
username: "",
password: "",
},
validators: {
username: ({ username }) =>
username.length == 0
? new Error("Must contain at least 1 char.")
: undefined,
password: ({ password }) =>
password.length == 0
? new Error("Must contain at least 1 char.")
: undefined,
},
onSubmitForm: ({ username, password }) => {
/// This scope guarantees all fields passed validations.
/// Optionally return a promise to set isSubmitting field to true for until promise resolves.
return api.signIn(username, password)
},
})
return (
<>
<input
value={values.username}
onChange={(e) => update("username", e.target.value)}
/>
<label>{validations.username.error?.message}</label>
{/*validations.username.checked */}
{/*validations.username.validating */}
<input
value={values.password}
onChange={(e) => update("password", e.target.value)}
/>
<label>{validations.password.error?.message}</label>
{/*validations.password.checked */}
{/*validations.password.validating */}
<button disabled={isSubmitting} onClick={() => submit()}>
Submit
</button>
</>
)
}