form-validation
Result
Loading...
Live Editor
function App() { const initData = { name: "", phone: "", gender: "", }; let gender = [ { name: "Male", isChecked: false, }, { name: "Female", isChecked: false, }, { name: "Other", isChecked: false, }, ]; const [data, setData] = useState(initData); const [error, setError] = useState({}); const [genders, setGenders] = useState(gender); // name -> space dont allow // ph -> textbox only number will allowed // gender -> checbox male,F Other // select only once function validate({ name, value }) { if (name === "name") { if (!value) { setError((prev) => ({ ...prev, name: "name is required" })); } else { setError((prev) => ({ ...prev, name: "" })); } } if (name === "phone") { let isNumber = Number.isNaN(Number(value)); if (isNumber) { setError((prev) => ({ ...prev, phone: "dont enter text" })); } else { setError((prev) => ({ ...prev, phone: "" })); } } } function handleChange(e) { const { name, value } = e.target; validate({ name, value }); setData((prev) => ({ ...prev, [name]: value.trim() })); } return ( <div className="App"> <input onChange={handleChange} type="text" name="name" placeHolder="name" /> {error.name && error.name} <br /> <input onChange={handleChange} type="text" name="phone" placeHolder="phone" /> {error.phone && error.phone} <br /> <p>Gender</p> {genders.map((each, i) => ( <div> {each?.name} <input key={each.name} checked={each.isChecked} type="checkbox" name="male" onChange={() => { const prevGender = [...genders]; let newData = prevGender.map((e, index) => { if (i === index) { e.isChecked = !e.isChecked; } else { e.isChecked = false; } return e; }); // prevGender[i].isChecked = !prevGender[i].isChecked; setGenders(newData); }} placeHolder="name" /> </div> ))} {JSON.stringify(data)} </div> ); }