0

I want to implement the functionality for checking email in the real-time in the customer register form, without submitting the form, need to check whether the email is already there or not and show an error or message. Can anyone help or suggest any reference link for the same ?

1 Answer 1

0

Refer below code

app/code/Vendor/Module/view/frontend/layout/customer_account_create.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="form.additional.info">
            <block class="Magento\Framework\View\Element\Template" name="check_email_availability" template="Vendor_Module::form/checkemailavailability.phtml"/>
        </referenceContainer>
    </body>
</page>

app/code/Vendor/Module/view/frontend/templates/form/checkemailavailability.phtml

<script type="text/x-magento-init">
    {
        "#email_address": {
            "Vendor_Module/js/checkEmailAvailability": {}
        }
    }
</script>

app/code/Vendor/Module/Controller/Index/IsEmailAvailable.php

<?php 

namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Framework\Validator\EmailAddress as EmailValidator;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\LocalizedException;

class IsEmailAvailable extends Action
{
    /**
     * @var Context
     */
    protected $context;

    /**
     * @var AccountManagementInterface
     */
    protected $accountManagement;

    /**
     * @var EmailValidator
     */
    private $emailValidator;

    /**
     * @var JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @param Context $context
     * @param AccountManagementInterface $accountManagement
     * @param EmailValidator $emailValidator
     * @param JsonFactory $resultJsonFactory
     */
    public function __construct(
        Context $context,
        AccountManagementInterface $accountManagement,
        EmailValidator $emailValidator,
        JsonFactory $resultJsonFactory
    ) {
        $this->context = $context;
        $this->accountManagement = $accountManagement;
        $this->emailValidator = $emailValidator;
        $this->resultJsonFactory = $resultJsonFactory;
        parent::__construct($context);
    }

    /**
     * Check if email already exists
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $resultJson = $this->resultJsonFactory->create();
        $email = $this->getRequest()->getParam('email');
        if (empty($email)) {
            return $resultJson->setData(['status' => false, 'message' => __('Email is a required field.')]);
        }
        if (!$this->emailValidator->isValid($email)) {
            return $resultJson->setData(['status' => false, 'message' => __('Please enter a valid email address (Ex: [email protected]).')]);
        }
        try {
            $isEmailAvailable = $this->accountManagement->isEmailAvailable($email);
            if($isEmailAvailable) {
                return $resultJson->setData(['status' => true, 'message' => __('Email address is available.')]);
            } else {
                return $resultJson->setData(['status' => false, 'message' => __('There is already an account with this email address.')]);
            }
        } catch (LocalizedException $e) {
            return $resultJson->setData(['status' => false, 'message' => __('Some error occurred while verifying email. Please try again.')]);
        }
    }
}

app/code/Vendor/Module/view/frontend/web/js/checkEmailAvailability.js

define([
    'jquery',
    'mage/url',
    'jquery/ui',
    'jquery/validate',
    'mage/validation'
], function ($, urlBuilder) {
    'use strict';

    $.widget('mage.checkEmailAvailability', {
        options: {
            formSelector: 'form.form-create-account',
            emailSelector: '#email_address',
            errorMsgSelector: '#email-error'
        },

        /**
         * Widget initialization
         * @private
         */
        _create: function () {
            var self = this;
            this.formSelector = this.options.formSelector;
            this.emailSelector = this.options.emailSelector;
            this.errorMsgSelector = this.options.errorMsgSelector;
            this.hasEmailError = false;
            this.errorMsg = '';
            this.errorMsgHtml = '';
            this.emailCheckTimeout = 0;
            this.checkDelay = 1000;
            this._bind();
        },

        /**
         * Event binding, will monitor change and paste events.
         * @private
         */
        _bind: function () {
            this._on(this.emailSelector, {
                'change': this.emailHasChanged,
                'paste': this.emailHasChanged
            });
            this._on(this.formSelector, {
                'submit': this.onSubmit
            });
        },

        /**
         * Call on email change.
         */
        emailHasChanged: function () {
            var self = this;
            clearTimeout(this.emailCheckTimeout);
            this.removeError();
            this.emailCheckTimeout = setTimeout(function () {
                this.hasEmailError = false;
                if (self.validateEmail()) {
                    self.isEmailAvailable($(self.emailSelector).val());
                }
            }, self.checkDelay);
        },

        /**
         * Call on form submit.
         */
        onSubmit: function (event) {
            var self = this;
            if (this.hasEmailError) {
                event.preventDefault();
                this.emailCheckTimeout = setTimeout(function () {
                    self.showError(self.errorMsg);
                }, self.checkDelay);
            }
        },

        /**
         * Show error message.
         */
        showError: function (error) {
            this.errorMsg = error;
            $(this.emailSelector).removeClass('valid');
            $(this.emailSelector).addClass('mage-error');
            this.errorMsgHtml = '<div id="email-error" class="mage-error">'+error+'</div>';
            $(this.emailSelector).after(this.errorMsgHtml);
            $(this.errorMsgSelector).show();
            $(this.emailSelector).focus();
        },

        /**
         * Remove error message.
         */
        removeError: function () {
            $(this.emailSelector).removeClass('mage-error');
            $(this.errorMsgSelector).remove();
        },

        /**
         * Local email validation
         */
        validateEmail: function (email) {
            var self = this,
                form = $(this.formSelector),
                validator;

            $(this.emailSelector).valid();
            validator = form.validate();
            return validator.check(this.emailSelector);
        },

        /**
         * Check if email available
         */
        isEmailAvailable: function (email) {
            var self = this;
            $.ajax({
                url: urlBuilder.build('frontName/index/isEmailAvailable'),
                type: 'post',
                context: this,
                data: {
                    email: email
                },
                dataType: 'json',
            }).done(function (response) {
                if (response['status']) {
                    self.hasEmailError = false;
                } else {
                    self.showError(response['message']);
                    self.hasEmailError = true;
                }
            });
        },
    });

    return $.mage.checkEmailAvailability;
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.