Reputation: 6778
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:
Upvotes: 0
Views: 1380
Reputation: 6778
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;
Upvotes: 0
Reputation: 418
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;
}
};
Upvotes: 1