Skip to content
This repository has been archived by the owner on Jun 30, 2022. It is now read-only.

Commit

Permalink
[IMPROVE] Centralized e-mail validation under a library function (#693)
Browse files Browse the repository at this point in the history
* Centralized e-mail regex usage

* moved constants out of the function
  • Loading branch information
cauefcr committed Mar 25, 2022
1 parent 12225f8 commit fb1b2ee
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/components/Form/index.js
Original file line number Diff line number Diff line change
@@ -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();
Expand All @@ -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')),
};
Expand Down
12 changes: 12 additions & 0 deletions src/lib/email.js
Original file line number Diff line number Diff line change
@@ -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);
}
};

0 comments on commit fb1b2ee

Please sign in to comment.