Hello I am new learner of react.
anybody please help me in form validation on(onchange) input Fields
<Form.Group className="mb-3" controlId="Username"> <Form.Label>Username</Form.Label> <Form.Control type="text" placeholder="Lastname" name='username' value={Validation} onChange={textchange}/> </Form.Group> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Label>Email address</Form.Label> <Form.Control type="email" placeholder="Enter email" name='email' value={Validation.email} onChange={emailchange}/> <Form.Text className="text-muted"> We'll never share your email with anyone else. </Form.Text> </Form.Group> <Form.Group className="mb-3" > <Form.Label>Password</Form.Label> <Form.Control type="password" placeholder="Password" name='password' autoComplete="on" onChange={passchange}
value={Validation.password}/>
</Form.Group>
<Form.Group className="mb-3" >
<Form.Check type="checkbox" label="Check me out" />
</Form.Group>Submit
2
Answers
For forms in React, you can use the
formik
package for react as it helps in validation and forms in general.For forms you can either use
useRef
if you don’t care for your component to re-render, or one ofuseState
anduseReducer
.Generally having too many states in your component (or in a form like this) is not good practice.
You can use
useReducer
as it helps manage your logic for theonChange
property of your entire form in one place.Generally the
onChange
property returns anevent
and the value in your field can be accessed this way:or using functions like you are:
and for validation you can check before setting your state of variable depending on the conditions you need to add.
I recommend you to use react-hook-form.
It’s the best library to manage forms in react.