skip to Main Content

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


  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.

    Login or Signup to reply.
  2. I recommend you to use react-hook-form.
    It’s the best library to manage forms in react.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search