From fb1b2ee4e29074e2a29f777fc3ddb3ac16be5d6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Felchar?= <11652381+cauefcr@users.noreply.github.com> Date: Fri, 25 Mar 2022 10:45:48 -0300 Subject: [PATCH] [IMPROVE] Centralized e-mail validation under a library function (#693) * Centralized e-mail regex usage * moved constants out of the function --- src/components/Form/index.js | 4 ++-- src/lib/email.js | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 src/lib/email.js diff --git a/src/components/Form/index.js b/src/components/Form/index.js index 6aad5e7d1..c2111b689 100644 --- a/src/components/Form/index.js +++ b/src/components/Form/index.js @@ -1,10 +1,10 @@ import { h } from 'preact'; import I18n from '../../i18n'; +import { validateEmail } from '../../lib/email'; import { createClassName, MemoizedComponent } from '../helpers'; import styles from './styles.scss'; - export class Form extends MemoizedComponent { static defaultHandleSubmit = (event) => { event.preventDefault(); @@ -25,7 +25,7 @@ export class Form extends MemoizedComponent { export const Validations = { nonEmpty: ({ value }) => (!value ? I18n.t('Field required') : undefined), - email: ({ value }) => (!/^\S+@\S+\.\S+/.test(String(value).toLowerCase()) ? I18n.t('Invalid email') : null), + email: ({ value }) => (validateEmail(String(value).toLowerCase()) ? null : I18n.t('Invalid email')), custom: ({ value, pattern }) => (new RegExp(pattern, 'i').test(String(value)) ? null : I18n.t('Invalid value')), }; diff --git a/src/lib/email.js b/src/lib/email.js new file mode 100644 index 000000000..1bab788e5 --- /dev/null +++ b/src/lib/email.js @@ -0,0 +1,12 @@ +const basicEmailRegex = /^[^@]+@[^@]+$/; +const rfcEmailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + +export const validateEmail = (email, options = { style: 'basic' }) => { + switch (options.style) { + case 'rfc': + return rfcEmailRegex.test(email); + case 'basic': + default: + return basicEmailRegex.test(email); + } +};