Skip to content

Instantly share code, notes, and snippets.

@humayunkabir
Last active December 7, 2021 13:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humayunkabir/6b09b69c081eab9d4da6b1e7449b88b6 to your computer and use it in GitHub Desktop.
Save humayunkabir/6b09b69c081eab9d4da6b1e7449b88b6 to your computer and use it in GitHub Desktop.
Validation hook for React Hook Form with Joi
import { useState } from 'react';
import useValidation from './hooks/useValidation';
import Joi from 'joi';
const schema = Joi.object({
email: Joi.string()
.email({ tlds: { allow: false } })
.required(),
password: Joi.string().min(8).required(),
});
const App = () => {
const [loading, setLoading] = useState(false);
const { register, onSubmit, onReset, errors } = useValidation(
schema,
(data) => {
setLoading(true);
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(data);
}, 2000);
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
})
.finally(() => {
setLoading(false);
});
}
);
return (
<>
<form onSubmit={onSubmit} onReset={onReset}>
<input
placeholder='Enter your email'
type='email'
{...register('email')}
/>
<small>{errors?.email?.message}</small>
<input
type='password'
placeholder='Enter your password'
{...register('password')}
/>
<small>{errors?.password?.message}</small>
<button type='submit' disabled={loading}>
Sign in
</button>
<button type='reset' disabled={loading}>
Reset
</button>
</form>
</>
);
};
export default App;
import { FormEvent } from 'react';
import {
useForm,
FieldErrors,
SubmitHandler,
UseFormRegister,
} from 'react-hook-form';
import { joiResolver } from '@hookform/resolvers/joi';
import { ObjectSchema } from 'joi';
export interface UseValidationReturn<T> {
register: UseFormRegister<T>;
onSubmit: (e: FormEvent) => Promise<void>;
onReset: (e: FormEvent) => void;
errors: FieldErrors;
}
const useValidation = <T>(
schema: ObjectSchema<T>,
callback: SubmitHandler<T>
): UseValidationReturn<T> => {
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<T>({ resolver: joiResolver(schema) });
const onSubmit = handleSubmit(callback);
const onReset = (e: FormEvent) => {
e.preventDefault();
reset();
};
return {
register,
onSubmit,
onReset,
errors,
};
};
export default useValidation;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment