Email Field Validation

PHOTO EMBED

Wed Jun 28 2023 06:41:09 GMT+0000 (Coordinated Universal Time)

Saved by @JISSMONJOSE #react.js #css #javascript

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,
                })}
              />




content_copyCOPY