diff --git a/src/components/TestForm/emailValidator.ts b/src/components/TestForm/emailValidator.ts new file mode 100644 index 0000000000000000000000000000000000000000..122f5018adbbb62b9709bab417277584f17c6a7f --- /dev/null +++ b/src/components/TestForm/emailValidator.ts @@ -0,0 +1,10 @@ +export const isEmailValid = (email: string): boolean => { + /** + * The following is the RFC 5322 valid email regex + * Hinted from question https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression + * More on http://emailregex.com/ + */ + // eslint-disable-next-line + const VALID_EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\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,}))$/; + return VALID_EMAIL_REGEX.test(String(email).toLowerCase()); +}; diff --git a/src/components/TestForm/index.tsx b/src/components/TestForm/index.tsx index a7479353a7f11b5054bf58a867d03272a62f038c..fea60f62beb129a8868668d8ba60ed70b88b60ab 100644 --- a/src/components/TestForm/index.tsx +++ b/src/components/TestForm/index.tsx @@ -2,6 +2,7 @@ import React, { useState } from 'react'; import { createStyles, makeStyles, Theme } from '@material-ui/core/styles'; import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button'; +import { isEmailValid } from './emailValidator'; const useStyles = makeStyles((theme: Theme) => createStyles({ @@ -34,21 +35,10 @@ export const Form: React.FC = () => { }; const [formValues, setFormValues] = useState<formData>(defaultValues); - const isEmailValid = (): boolean => { - /** - * The following is the RFC 5322 valid email regex - * Hinted from question https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression - * More on http://emailregex.com/ - */ - // eslint-disable-next-line - const VALID_EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\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,}))$/; - return VALID_EMAIL_REGEX.test(String(formValues.email).toLowerCase()); - }; - const handleSubmit = (event: React.FormEvent): void => { event.preventDefault(); const errors: Array<string> = []; - if (!isEmailValid()) { + if (!isEmailValid(formValues.email)) { errors.push('email'); console.log('Email address not valid'); } else {