npm install react-hook-form //installation
//react hook form with tailwind css
import React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit } = useForm();
const onSubmit = data => console.log(data);
return (
<form className="w-full" onSubmit={handleSubmit(onSubmit)}>
<div className="form-control w-full mb-5">
<label className="">
<span className="text-secondary font-semibold text-lg">
Email
</span>
</label>
<input
type="text"
placeholder="example@email.com"
className="input input-bordered w-full rounded-full"
{...register('email', {
required: {
value: true,
message: 'Email Required !!!',
},
pattern: {
value: /^[^s@]+@[^s@]+.[^s@]+$/i,
message: 'Invalid Email Provided !!!',
},
})}
/>
<label className="level font-bold">
{errors.email?.type === 'required' && (
<span className="label-text-alt text-red-500">
{errors.email.message}
</span>
)}
{errors.email?.type === 'pattern' && (
<span className="label-text-alt text-red-500">
{errors.email.message}
</span>
)}
</label>
</div>
<div className="form-control w-full">
<label className="">
<span className="text-secondary font-semibold text-lg">
Password
</span>
</label>
<input
type="password"
placeholder="abcd123$"
className="input input-bordered w-full rounded-full"
{...register('password', {
required: {
value: true,
message: 'Password Required !!!',
},
pattern: {
value: /(?=.*[!#$%&?^*@~() "])(?=.{8,})/,
message:
'Password Must be 8 char including a special char !!!',
},
})}
/>
<label className="level font-bold">
{errors.password?.type === 'required' && (
<span className="label-text-alt text-red-500">
{errors.password.message}
</span>
)}
{errors.password?.type === 'pattern' && (
<span className="label-text-alt text-red-500">
{errors.password.message}
</span>
)}
</label>
</div>
<input type="submit" />
</form>
);
}
import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from "react-redux";
import useForm from 'react-hook-form';
function SampleForm() {
const { register, handleSubmit } = useForm();
const onSubmit = data => {
alert(JSON.stringify(data));
};
return (
<div className="App">
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="firstName">First Name</label>
<input name="firstName" placeholder="bill" ref={register} />
</div>
<div>
<label htmlFor="lastName">Last Name</label>
<input name="lastName" placeholder="luo" ref={register} />
</div>
<div>
<label htmlFor="email">Email</label>
<input name="email" placeholder="bluebill1049@hotmail.com" type="email" ref={register} />
</div>
<button type="submit">Submit</button>
</form>
</div>
);
}
class Sample extends Component {
constructor(props) {
super(props);
}
render() {
return <SampleForm />;
}
}
export default connect()(Sample);
const rootElement = document.getElementById('root');
ReactDOM.render(<Sample />, rootElement);