Validation to prevent brand names being in the email field?

Viewed 36

So, I have this list of some brandnames:

const blackListedDomains = [
  'facebook',
  'google',
  'amazon',
  'netflix',
  'hotmail',
  'microsoft',
  'gmail',
  'yahoo',
]

which I need to prevent users to enter in the email field, what Schema could be built using Yup Package.

For example, I am trying this way:

const DomainSchema = Yup.object().shape({
      subdomain: Yup.string()
        .required('Required')
        .lowercase()
        .notOneOf(
          blackListedDomains,
          'Cannot use trademarked names in domain!',
        ),
    })

But, I don't know how to get it from the email string, for example, if user inputs xyz@google.xyz, then how to extract google from the email string and then iterate it over the domain names list to find if it exists there and then show an error message ?

1 Answers

You can use test function of yup library to create a custom validation rule like this:

const DomainSchema = Yup.object().shape({
  email: Yup.string()
    .required("Required")
    .lowercase()
    .email("Not a valid mail")
    .test(
      "is-not-blacklist",
      "Cannot use trademarked names in domain!",
      (value) => {
        if (value) {
          const currentDomain = value.substring(
            value.indexOf("@") + 1,
            value.indexOf(".")
          );

          return !blackListedDomains.includes(currentDomain);
        }
      }
    )
});

You can take a look at this sandbox for a live working example of this solution.

Related