Created
February 15, 2022 02:33
-
-
Save mhaecal/e248028947ef6835ed4707b486437a79 to your computer and use it in GitHub Desktop.
React Hook Form Validation with Error Message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { useForm } from 'react-hook-form' | |
import { ErrorMessage } from '@hookform/error-message' | |
function App() { | |
// prettier-ignore | |
const { register, handleSubmit, formState: { errors } } = useForm() | |
const onSubmit = ({ username, password }) => { | |
alert(`Username: ${username}, Password: ${password}`) | |
} | |
return ( | |
<form onSubmit={handleSubmit(onSubmit)}> | |
<div> | |
<input | |
{...register('username', { | |
required: 'Username required', | |
minLength: { | |
value: 8, | |
message: 'Minimal 8', | |
}, | |
})} | |
type="text" | |
placeholder="Username" | |
/> | |
{/* if as component as={<Text />} */} | |
<ErrorMessage errors={errors} name="username" as="div" /> | |
</div> | |
<div> | |
<input | |
{...register('password', { | |
required: 'Password required', | |
minLength: { | |
value: 6, | |
message: 'Minimal 6', | |
}, | |
})} | |
type="text" | |
placeholder="Password" | |
/> | |
{/* if as component as={<Text />} */} | |
<ErrorMessage errors={errors} name="password" as="div" /> | |
</div> | |
<button>Login</button> | |
</form> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment