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
|
61 Discussions
|
Please Login in order to post a comment
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;
There are some error in the test cases for date. Until somebody from HackerRank fix it use the below code for your purpose.
All test cases passed ✅.
The test case is failing because it hardcodes a fixed date ("2025-04-12"). This is not a best practice.