const [formErrors, setFormErrors] = useState<UserRegistrationDetails>({ firstName: '', lastName: '', gender: '', dateOfBirth: '', primaryEmail: '', secondaryEmail: '', primaryMobileNumber: '', secondaryMobileNumber: '', service: '', }); const validateEmail = (email: string) => { const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/; return emailRegex.test(email); }; const handleUserRegistrationForm = () => { const handleEmptyField = (fieldName: string, fieldValue: string, errorMessage: string) => { if (!fieldValue) { errors[fieldName] = errorMessage; } }; handleEmptyField('firstName', firstName, 'First name is required'); handleEmptyField('lastName', lastName, 'Last name is required'); handleEmptyField('primaryEmail', primaryEmail, 'Primary email is required'); handleEmptyField('primaryMobileNumber', primaryMobileNumber, 'Primary mobile number is required'); handleEmptyField('dateOfBirth', dateOfBirth, 'Date of birth is required'); if (primaryEmail.trim() !== '') { if (!validateEmail(primaryEmail)) { errors.primaryEmail = 'Invalid email'; } } setFormErrors(errors); } <input type="email" className="form-control email-input" id="email" placeholder="abc@babc.com" // onchange onChange={(e) => setPrimaryEmail(e.target.value)} {...register('primaryEmail', { required: true, })} />
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter