I'm new to react and programing. I am trying to implement a email validation using this platform. https://upmostly.com/tutorials/form-validation-using-custom-react-hooks.
Desire outcome: Users must enter an email, otherwise it will show red text below input field. If you think I should use another library like react-hook-forms, please let me know
Please check out my work below. Thank you in advance.
Not working: I still click submit and the message(Email is invalid) doesn't come up
This is the step where the email should be validated
const Step3 = (props) => {
const [values, setValues] = useState({});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const {
handleChange,
handleSubmit,
} = useForm(validate);
useEffect(() => {
if (Object.keys(errors).length === 0 && isSubmitting) {
}
}, [errors]);
const onChange = (event) => {
event.persist();
setValues(values => ({ ...values, [event.target.name]: event.target.value }));
};
const onSubmit = (event) => {
if (event) event.preventDefault();
setErrors(validate(values));
setIsSubmitting(true);
};
return (
<WizardStep>
<WizardProgress className="text-primary">
Question {props.currentStep}/{props.totalSteps}
</WizardProgress>
<StepTitle>What is your email address?</StepTitle>
<WizardFormWrapper>
<WizardFormGroup controlId="userEmailGroup">
<StyledTextInput
type="email"
autoComplete="off"
className={`input ${errors.email && 'is-danger'}`}
name="email"
label="Email"
placeholder="Email"
onChange={onChange}
value={values.email}
required
/>
{errors.email && (
<p className="help is-danger">{errors.email}</p>
)}
</WizardFormGroup>
</WizardFormWrapper>
<WizardButtonGroup>
<Link to="/feed">
<SubmitButton primary="true" onSubmit={onSubmit}>
Submit
</SubmitButton>
</Link>
</WizardButtonGroup>
</WizardStep>
);
};
This is the validation method
export default function validate(values) {
let errors = {};
if (!values.email) {
errors.email = 'Email address is required';
} else if (!/\S+@\S+\.\S+/.test(values.email)) {
errors.email = 'Email address is invalid';
}
if (!values.password) {
errors.password = 'Password is required';
} else if (values.password.length < 8) {
errors.password = 'Password must be 8 or more characters';
}
return errors;
};