Home > database >  How to show form validation error in react
How to show form validation error in react

Time:06-21

I do all thing my validation message can print on console but not on page i want my validation error can also shown on form

this is my App.js i use react 18.2.0 version on my machine

I use this as shown error on page <p style={{color: "Red"}}>{errors ? errors.Name : '' }

import React, { useState } from "react";

function App(){

  const[Name,setName]= useState('');
  const[Email,setEmail]=useState('');
  const[Password,setPassword]=useState('');
  const errors={};


  const handleChange = (e) =>{
    console.log(e.target.value);
    setName(e.target.value);

  }
  const handleEmailChange =(e)=>{
    setEmail(e.target.value);
  }
  const handlePasswordChange =(e)=>{
    setPassword(e.target.value);
  }

  const handleSubmit = event => {
    event.preventDefault();
    console.log(`Name:  ${Name}  \n
            email: ${Email} \n
            Password: ${Password} \n `);
  //console.log(typeof(Name))
            if(!Name || !Email || !Password) {
              console.log('here');
             
                errors.Name="All Fields Are Required!";
            console.log(errors)
                 // return errors;

            }
  };
return(
    <div>
      <h1>Form</h1>
      <form onSubmit={handleSubmit}>
        <div>
        <label>Enter Your Name: </label>
        <input type="text" value={Name} onChange={handleChange}></input>
        </div>
        <p style={{color: "Red"}}>{errors ?  errors.Name : '' }</p>
        <div>
        <label>Enter your Email:  </label>
        <input type="email"  value={Email} onChange={handleEmailChange}></input>
        </div>
        {/* <p style={{color: "Red"}}>{FormErrors.Email}</p> */}
        <div>
        <label>Enter your Password:  </label>
        <input type="password"  value={Password} onChange={handlePasswordChange}></input>
        </div>
        {/* <p style={{color: "Red"}}>{FormErrors.Password}</p> */}
        <button>Submit</button>
      </form>
    </div>
  );
}

Like This

i want if all field is required they give error on all column like name is required email is required password is required i use this else if but it show error one by one like if i empty all field it will only show error on Name field not Password or email field

 if (!Name) {
      setErrors({Name: "Name is Required!" });
       console.log(errors.Name);
            }
            else if(!Email){
              setErrors({Email: "Email is Required!"});
            }
            else if(!Password){
              setErrors({Password:"password is Required!"});
            }        
  };

CodePudding user response:

react is not able to re-render your component instead use useState to setErrors

try this

 const [errors, setErrors] = useState({});

 
  const handleSubmit = event => {
    event.preventDefault();
    console.log(`Name:  ${Name}  \n
            email: ${Email} \n
            Password: ${Password} \n `);
    //console.log(typeof(Name))
       if (!Name) {
      setErrors((prevState) => {
        return {
          ...prevState,
          Name: "Name is Required!",
        };
      });
    } else {
      setErrors((prevState) => {
        return {
          ...prevState,
          Name: "",
        };
      });
    }
  };

CodePudding user response:

There is a mistake in your code.

No Rerender for Error You could make an Error state for that like this

const [errors, setErrors] = useState({});

const handleSubmit = (event) => {
event.preventDefault();

    if (!Name || !Email || !Password) {
    setErrors("All Fields Are Required!");
}

};

In JSX , Add this at top of Form

 <p style={{color: "Red"}}>{errors ?  errors: '' }</p>
  • Related