1

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

3
  • Can you post your code? Commented Feb 17, 2023 at 7:24
  • sir actually i have done only html code i dont know how to validate forms in react Commented Feb 17, 2023 at 7:25
  • Does this answer your question? How do I add validation to the form in my React component? Commented Feb 17, 2023 at 7:48

2 Answers 2

1

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 of useState and useReducer.

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 the onChange property of your entire form in one place.

Generally the onChange property returns an event and the value in your field can be accessed this way:

onChange={event=>{setValue(event.target.value)}}

or using functions like you are:


function handleChange (event) {
setValue(event.target.value);
}
...
<input value={value} onChange={handleChange} />

and for validation you can check before setting your state of variable depending on the conditions you need to add.

Sign up to request clarification or add additional context in comments.

Comments

1

I recommend you to use react-hook-form. It's the best library to manage forms in react.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.