Home > front end >  I have made a form I want to put an alert if any of the field is empty and also want the form to not
I have made a form I want to put an alert if any of the field is empty and also want the form to not

Time:01-11

I have made a form I want to put an alert if any of the field is empty and also want the form to not accept data if the field is empty.

i have not tried anything coz not able to find a solution for it. below is the code i have done till now. I have linked the form to a database but u want the form not to accept data if the any of the field is empty and send alert that the fields are empty.

`import React,{useState} from 'react'
import Axios from 'axios'

function PostForm(){
    const url ="http://localhost:5000/qo"
    const [data, setData] = useState({
        Employee_name:"",
        Employee_id:"",
        Employee_address:"",
        Employee_post: ""
    })

    function submit(e){
        e.preventDefault();
        Axios.post(url,{
            Employee_name: data.Employee_name,
            Employee_id: data.Employee_id,
            Employee_address: data.Employee_address,
            Employee_post: data.Employee_post
        })
        .then(res=>{
            console.log(res.data)
        })
        alert('Employee Data Saved')
    }

    

    function handle(e){
        const newdata = {...data}
        newdata[e.target.id] = e.target.value
        setData(newdata)
        console.log(newdata)
    }
    return(
        
        <div>
            <div>
                <h2>Registration Form</h2>
            </div>
            <form onSubmit={(e)=> submit(e)}>
                <label>Employee Name : </label>
                <input onChange={(e)=>handle(e)} id="Employee_name" value={data.Employee_name} placeholder ="Employee name" type ="text"></input>
                <br/>
                <br/>
                <label>Employee id : </label>
                <input onChange={(e)=>handle(e)} id="Employee_id" value={data.Employee_id} placeholder ="Employee id" type ="number"></input>
                <br/>
                <br/>
                <label>Employee Address : </label>
                <input onChange={(e)=>handle(e)} id="Employee_address" value={data.Employee_address} placeholder ="Employee address" type ="text"></input>
                <br/>
                <br/>
                <label>Employee Position : </label>
                <input onChange={(e)=>handle(e)} id="Employee_post" value={data.Employee_post} placeholder ="Employee position" type ="text"></input>
                <br/>
                <br/>
                <button>Submit</button>
            </form>
        </div>
    )
}

export default PostForm;`

CodePudding user response:

Just add the required in all inputs

<input ...all_things required={true} />
  • Related