Home > Blockchain >  create a react input form with validation
create a react input form with validation

Time:02-15

i there, i am working on react input form but problem is don't know how to validate, also not getting value on onChange , please have a look on my code.

i have create a array which value i need to update using input form

useEffect(() => {
    let arr = [];
    for (let i = 0; i < Number(localStorage?.getItem("users")); i  ) {
      arr.push({
        username: localStorage.getItem("userName"),
        user_email: localStorage.getItem("userEmail"),
        password: "",
        button: "",
        designation: "",
        country: "",
        city: "", 
        company_name: "",
      });
    }
    setUserRemaining(arr);
  }, []);

then i have input form , which i want with validation

{userRemaining.map((element, index) => {
                  return (
                    <div className="block2">
                      <input type="text" name="username" value='' onChange={(event) =>  handleChange(event, index)}/>
                      
                      <div className="add" onClick={() => addUser(element, index)}>
                        <span>
                          <img src={img1} />
                        </span>
                        Add
                      </div>
                    </div>
                  );
                })}

at last there is my handleChange method i've tried.

const handleChange = (event, index) => {
    const updatedUser = userRemaining.map((users, index1) => {
      if (index1 == index) {
        return {
          ...users,
          [event.target.name]: event.target.value,
        };
      } else {
        return users;
      }

for more details i am providing a link of file too. https://codesandbox.io/s/compassionate-gauss-pq2wr?file=/src/App.js

CodePudding user response:

Hello I pretty recommend you use react hooks form https://react-hook-form.com/get-started#Applyvalidation Its pretty easy input validations using this library Here an small example

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 onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName", { required: true, maxLength: 20 })} />
      <input {...register("lastName", { pattern: /^[A-Za-z] $/i })} />
      <input type="number" {...register("age", { min: 18, max: 99 })} />
      <input type="submit" />
    </form>
  );
}
  • Related