I have a component using a regex expression to check for email format validity. I have this attached as an onBlur function for the input that also runs on load as part of the React hook useEffect as soon as the page loads. The function is supposed to check for an empty field and fire an error message prompting the user to enter an email address or select opt out. If the email entered is the wrong format a separate error should fire. On load everything runs as expected with the initial error firing for an empty input. The issue occurs after a user enters the input field and leaves. The function fires and sets the error prompting a user to enter a valid email even when the input field is empty. I've swapped things out and initially tried to get around this by setting the first check as if(value === undefined || '' but so far I'm getting the same behavior. Any suggestions?
Functions for validation
function validateEmail(value) {
const errors = { hasError: false }
if (value === undefined || '') {
errors.email = 'Enter a valid email address or select Email Opt Out'
errors.hasError = true
return errors
}
if (!/\S+@\S+\.\S+/.test(value)) {
errors.email = 'Enter a valid email address'
errors.hasError = true
return errors
}
return errors
}