Fast & Precise Email Validation in JavaScript – EveryMail

Category: Javascript | December 13, 2024
AuthorJohnMomboko
Last UpdateDecember 13, 2024
LicenseMIT
Tags
Views40 views
Fast & Precise Email Validation in JavaScript – EveryMail

EveryMail is a lightweight and configurable JavaScript email validation library written in TypeScript.

It provides both basic checks and advanced validation options to meet your specific needs.

Features:

  • Basic Validation: Dectec if an email follows the correct format (e.g., ‘[email protected]’). This simple validation is perfect for general use cases where domain restrictions aren’t required.
  • Domain Restrictions: You can restrict email addresses to specific allowed domains or reject certain disallowed domains. This is useful for applications where only emails from particular domains are acceptable, such as company registrations or approved partners.
  • Customizable Error Messages: The library allows you to set custom error messages, so users receive clear feedback when their email doesn’t meet the validation criteria.

How to use it:

1. Install EveryMail using your preferred package manager:

# Yarn
$ yarn add everymail
# NPM
$ npm install everymail

2. Import the validateEmail function into your JavaScript file:

import validateEmail from "everymail";
// OR
const validateEmail = require("everymail").default;

3. Perform a basic email address check. It returns a Promise that resolves with a success message if the email is valid or rejects with an error message if it is not.

const email = "[email protected]";
validateEmail(email)
  .then((message) => console.log(message))
  .catch((error) => console.error(error));
  // => "The email address is valid."

4. You can specify a list of allowed domains. If you specify allowed domains, only emails with those domains will be accepted.

const email = "[email protected]";
const options = {
  allowedDomains: ["cssscript.com", "gmail.com"],
};
validateEmail(email, options)
  .then((message) => console.log(message))
  .catch((error) => console.error(error));
  // => "The email address is valid."

5. You can also specify a list of disallowed domains. Emails with these domains will be rejected.

const email = "[email protected]";
const options = {
  disallowedDomains: ["yahoo.com"],
};
validateEmail(email, options)
  .then((message) => console.log(message))
  .catch((error) => console.error(error));
  // => "The domain of this email is not authorized."

6. Define custom error messages for rejected emails:

const email = "[email protected]";
const options = {
  allowedDomains: ["cssscript.com"],
  errorDisallowedDomainMessage: "Domain not allowed."
};
validateEmail(email, options)
  .then((message) => console.log(message))
  .catch((error) => console.error(error));
  // => Output: "Domain not allowed."

You Might Be Interested In:


Leave a Reply