0

I'm using React and Yup to validate an email address.

My schema looks like this:

const registrationSchema = yup.object().shape({
  email: yup.string().email().required()
})

And my code like this:

const handleOnSubmit = async () => {
    const formData = {
      email: props.emailInput
    }
    const isValid = await registrationSchema.isValid(formData)
    setInputErrorState(isValid ? false : true)
  }

The code above is doing the validation, but if I input a non-ASCII character like a Japanese or Chinese character it doesn't work. For example: ハロー@ハロー.com is passing the validation.

How can I allow only ASCII or romanji characters in my validation with YUP?

Ideal scenario:

  • attack.on.titan@gmail.com ✅
  • black@clover.com ✅
  • ハロー@ハロー.com ❌
Alfrex92
  • 6,278
  • 9
  • 31
  • 51

2 Answers2

1

Try this out using Regex

 const isEmail = email => {
         const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

         if (re.test(String(email).toLowerCase())) {
              return email;
         } else {
             return false;
         }
   };
Ibrahim shamma
  • 399
  • 5
  • 13
0

I removed yup and I used the answer suggested by Ibrahim shamma.

Here is the solution (RFC5322 compliant):

utils.tsx

// Regex taken from https://emailregex.com/
export const isEmail = email => {
  const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  if (re.test(String(email).toLowerCase())) {
    return true;
  }
  return false;
};

Component/index.tsx

import React from 'react';
import {isEmail} from '../utils'
export interface ComponentInterface {
 emailInput:string
 setEmailInput: (e: any) => void
}
 
const Component : React.FC<ComponentInterface> = (props:ComponentInterface) => {
 const [inputErrorState, setInputErrorState] = useState(false)
  const handleOnChange = (e) => {
    if (inputErrorState) {
      setInputErrorState(false)
    }
    props.setEmailInput(e.target.value)
  }
  const handleOnSubmit = () => {
    const isValid = isEmail(props.emailInput)
    setInputErrorState(isValid ? false : true)
  }
  return ( <div> 
           <input
            type='email'
            id='props.emailInput'
            value={emailInput}
            onChange={handleOnChange}
          ></input>
        {inputErrorState && (
          <p>Your error message</p>
        )}
 </div> );
}
 
export default Component;
Alfrex92
  • 6,278
  • 9
  • 31
  • 51