We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- React
- Forms
- Employee Validation
- Discussions
Employee Validation
Employee Validation
Sort by
recency
|
63 Discussions
|
Please Login in order to post a comment
Adjusted the time to pass test as the date is old.
I don't know why people are using useEffect or useReduce, but my following code with only useState is working:
Note: the day of today in the problem is 12/31/2024 instead of the actual date of today.
A much simpler implementation without useEffect. This is using useReducer which is much preferred in cases like creating forms.
test data should be updated, since it is using old joining date value to check future date or not.
Thanks
import React,{useEffect, useState} from "react";
function EmployeeValidationForm() { const [user, setUser] = useState({name:"",email:"",employeeId:"",joiningDate:""}); const [error, setError] = useState({name:"",email:"",employeeId:"",joiningDate:""}); const [isFormValid, setIsFormValid] = useState(true);
useEffect(()=>{ if(validation()){ setIsFormValid(false); } },[user]);
const validation =()=>{ let isValid=true; let newError = {name:"",email:"",employeeId:"",joiningDate:""};
if(!user.name.trim() || user.name.trim().length < 4){ newError.name="Name must be at least 4 characters long and only contain letters and spaces"; isValid=false; } const emailRegex = /^[^\s@]+@[^\s@]+.[^\s@]+/; if(!empIdRegex.test(user.employeeId)){ newError.employeeId = "Employee ID must be exactly 6 digits" isValid=false; } if(!user.joiningDate.trim() || user.joiningDate > "2024-12-31"){ newError.joiningDate = "Joining Date cannot be in the future" isValid=false; } setError(newError); return isValid; }
const handleChange=(e)=>{ e.preventDefault(); const {name, value}=e.target; setUser((prev)=>({ ...prev, }));
};
const handleSubmit =()=>{ if(validation()){ setUser({name:"",email:"",employeeId:"",joiningDate:""}); setError({name:"",email:"",employeeId:"",joiningDate:""}); setIsFormValid(false); }else{ console.log("Validation Failed."); } }; return ( {error.name && {error.name}
} {error.email && {error.email} } {error.employeeId && {error.employeeId} } {error.joiningDate && {error.joiningDate} } Submit ); }export default EmployeeValidationForm;