Mailcheck - Documentation

What is Mailcheck?

Mailcheck is a JavaScript library designed to detect and suggest corrections for potentially misspelled or incorrectly formatted email addresses as users type. It operates client-side, providing immediate feedback without requiring server-side interaction. Mailcheck analyzes the entered email address against a variety of patterns and a (configurable) list of known domain names, identifying likely typos and offering accurate suggestions. It’s lightweight and easily integrated into existing web forms.

Why use Mailcheck?

Using Mailcheck significantly improves the user experience by preventing email entry errors. Incorrectly entered email addresses lead to failed deliveries, frustrated users, and lost opportunities. Mailcheck proactively addresses this issue by:

Key Features and Benefits

Installation and Setup

Mailcheck can be easily installed via npm or a CDN.

1. Using npm:

npm install mailcheck

Then, import it into your JavaScript code:

import Mailcheck from 'mailcheck';

2. Using a CDN (e.g., jsDelivr):

Add the following script tag to your HTML file:

<script src="https://cdn.jsdelivr.net/npm/mailcheck@latest/dist/mailcheck.min.js"></script>

After including Mailcheck, you can initialize it using the following code:

const emailInput = document.getElementById('email'); // Replace 'email' with your input's ID

Mailcheck.run({
  email: emailInput,
  suggested: function(element, suggestion) {
    // Handle the suggestion, for example, display it to the user.
    console.log("Suggested email:", suggestion); // Or display it in a tooltip/popup etc
  },
  empty: function(element) {
    // Handle the case where the email field is empty.
  }
});

Remember to replace 'email' with the actual ID of your email input field. The suggested function receives the input element and the suggested email address, allowing you to customize how the suggestion is presented to the user. The empty function handles cases where the email input is empty. Consult the Mailcheck documentation for further customization options and advanced usage.

Core Functionality

Using the mailcheck Function

The core of Mailcheck lies in its run() function. This function takes a configuration object as its argument, defining how Mailcheck should operate and handle suggestions. The minimum required configuration includes an email property, specifying the input element where the email address is entered.

Mailcheck.run({
  email: document.getElementById('emailInput'),
  suggested: function(element, suggestion) {
    // Handle the suggestion here
  }
});

This code snippet initiates Mailcheck on the element with the ID “emailInput”. The suggested function (detailed below) is crucial for processing any suggested corrections. Failure to provide a suggested callback will result in no visible output from Mailcheck.

Understanding the suggested Property

The suggested property within the configuration object is a callback function. It’s triggered whenever Mailcheck identifies a potential misspelling or incorrect formatting and generates a suggestion. This function receives two arguments:

Handling full and domain Suggestions

The suggestion object passed to the suggested callback function may contain either or both of the properties: full and domain.

Example handling both types:

suggested: function(element, suggestion) {
  if (suggestion.full) {
    // Display the full suggested email address:  suggestion.full
    console.log("Full suggestion:", suggestion.full);
    //Example: element.value = suggestion.full; // Replace user input with full suggestion
  } else if (suggestion.domain) {
    // Use the suggested domain and keep the user's local-part
    const localPart = element.value.split('@')[0];
    const suggestedEmail = `${localPart}@${suggestion.domain}`;
    console.log("Domain suggestion:", suggestedEmail);
    //Example: element.value = suggestedEmail;
  }
}

Customizing Suggestion Matching

By default, Mailcheck uses a built-in list of domains. For more control, you can customize this. You can provide a custom list of domains using the domains property in the configuration object.

Mailcheck.run({
  email: document.getElementById('emailInput'),
  domains: ['example.com', 'mydomain.net', 'anotherdomain.org'],
  suggested: function(element, suggestion) {
    //Handle suggestion
  }
});

This will restrict suggestions to only those domains included in the domains array. This is particularly useful for enforcing company-specific email addresses.

Asynchronous Operation

Mailcheck’s operations are predominantly synchronous. The suggested callback is executed immediately after a suggestion is found. There’s no inherent asynchronous behavior in the core run() function. Any asynchronous operations (like fetching additional data or making API calls to validate domains) would need to be implemented separately within your suggested callback function. However, keep in mind that introducing asynchronous tasks within the callback might affect the immediate feedback nature of Mailcheck.

Advanced Usage

Integrating with Form Validation

Mailcheck can be seamlessly integrated with existing form validation mechanisms. Instead of simply displaying suggestions, you can use the information from Mailcheck to enhance your validation process. For example, you can prevent form submission if Mailcheck suggests a correction and the user hasn’t accepted it.

const form = document.getElementById('myForm');
const emailInput = document.getElementById('email');

Mailcheck.run({
  email: emailInput,
  suggested: function(element, suggestion) {
    // If suggestion exists and user hasn't corrected, show error
    if (suggestion.full && element.value !== suggestion.full) {
      // Add error styling or message
      element.classList.add('error');
      // Prevent form submission - depends on your validation library
      form.addEventListener('submit', (event) => {
          event.preventDefault();
          alert("Please correct your email address.");
      });
    } else {
      element.classList.remove('error');
    }
  }
});

This example adds an error class to the email input if a suggestion exists but the user hasn’t corrected the email address. Remember to adapt the form submission prevention to your specific form validation setup.

Creating Custom Suggestion Handlers

The suggested callback provides a flexible mechanism to customize how suggestions are presented. You can go beyond simple console logs or alerts by creating visually appealing and user-friendly interfaces. This might involve:

Remember to consider the user experience when designing your custom handler. Avoid intrusive or disruptive behaviors.

Handling Multiple Email Fields

Mailcheck can be easily extended to handle multiple email fields on a single page. Simply instantiate Mailcheck.run() for each email input element individually:

const emailInput1 = document.getElementById('email1');
const emailInput2 = document.getElementById('email2');

Mailcheck.run({ email: emailInput1, suggested: handleSuggestion });
Mailcheck.run({ email: emailInput2, suggested: handleSuggestion });

function handleSuggestion(element, suggestion) {
  //Handle suggestion for both inputs - use element to identify the specific input
  if (suggestion.full) {
    console.log(`Suggestion for ${element.id}:`, suggestion.full);
  }
}

This code initializes Mailcheck for both email1 and email2, using a single handleSuggestion function for consistency. The element parameter within the callback helps identify the specific input field that triggered the suggestion.

Internationalization and Localization

Mailcheck primarily handles the email address structure, not the text displayed to the user. Internationalization and localization of messages (error messages, suggestions, etc.) needs to be handled separately within your custom suggestion handlers. You can use libraries such as i18next to manage translations and dynamically load appropriate messages based on the user’s locale.

Performance Optimization

For performance-critical applications, consider these optimizations:

Remember to profile your application to identify specific performance bottlenecks before applying optimizations.

API Reference

mailcheck(email, options, callback)

The primary function for using Mailcheck is mailcheck(). Although Mailcheck.run() is often used for easier integration, understanding the underlying mailcheck() function provides deeper control. It takes three arguments:

options Parameter Details

The options object allows for fine-grained control over Mailcheck’s operation. The most commonly used options are:

callback Function Details

The callback function is executed after Mailcheck has completed its analysis. It receives a single argument:

Return Values

The mailcheck() function itself does not return a value. All results are passed to the provided callback function.

Error Handling

Mailcheck itself doesn’t throw errors in the traditional sense. However, invalid input (e.g., an empty email string or an incorrectly formatted options object) may result in the callback function being called with a result object containing no suggestion (suggestion: null). Thorough input validation before calling mailcheck() is recommended to avoid unexpected behavior. Furthermore, ensuring error handling within your custom empty and suggested callbacks is crucial for a robust implementation. These callbacks can handle cases where the email input is empty or where an unexpected result is returned from Mailcheck’s internal algorithms.

Troubleshooting

Common Issues and Solutions

Debugging Tips

Community Support and Resources

Contributing to Mailcheck

This section assumes you wish to contribute to the Mailcheck project. If the project doesn’t accept contributions, this section is not applicable. Please check the project’s repository for contribution guidelines before proceeding.

Setting up the Development Environment

  1. Fork the Repository: Create a fork of the official Mailcheck repository on GitHub.

  2. Clone your Fork: Clone your forked repository to your local machine using Git:

    git clone <your_fork_url>
  3. Install Dependencies: Navigate to the project directory and install the necessary dependencies using npm or yarn:

    npm install
    # or
    yarn install
  4. Set up a Development Server (if applicable): Some projects might require a development server for testing purposes. Refer to the project’s README or documentation for instructions on setting up the development server. This might involve using tools like Webpack, Parcel, or similar build systems.

Coding Style Guidelines

Adhere to the existing coding style used in the Mailcheck project. This typically involves:

Testing and Code Reviews

Submitting Pull Requests

  1. Create a Branch: Create a new branch for your changes using Git:

    git checkout -b <your_branch_name>
  2. Make your Changes: Implement your changes, ensuring they adhere to the coding style guidelines and are thoroughly tested.

  3. Commit your Changes: Commit your changes with clear and concise commit messages:

    git add .
    git commit -m "Your descriptive commit message"
  4. Push your Branch: Push your branch to your forked repository:

    git push origin <your_branch_name>
  5. Create a Pull Request: On GitHub, create a pull request from your branch to the main branch of the original Mailcheck repository. Provide a clear description of your changes and address any feedback provided during the code review process. Follow any specific contribution guidelines provided by the project maintainers.