1

I'm developing a custom form with a username that require validation at server side to check if the username exists. How can I apply the remote method of jquery validation plugin in Magento 2?

1 Answer 1

8

add remote property for 'data-validate' attribute. example:

<input name="email" id="email" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" value="" class="input-text" type="email" data-validate="{required:true, 'validate-email':true, 'remote':'<?php /* @escapeNotVerified */ echo $block->getValidateEmailAction(); ?>'}"/>

Here $block->getValidateEmailAction(); should be return link. example:

public function getValidateEmailAction()
{
    return $this->getUrl('stackexchange/index/validate', ['_secure' => true]);
}

And validate controller should be

namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\Action;

class Validate extends Action
{
    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $resultJson = $this->resultJsonFactory->create();
        $data = $this->getRequest()->getParam('email');
        $resultJson->setData('true');
        /*
        if(true) {
            $resultJson->setData('true');
        } else {
            $resultJson->setData('That name is already taken, try peter123 instead');
        }
        */
        return $resultJson;
    }
}
6
  • I make a controller to handle the validation. public function execute() { return true; } It returns Invalid return type
    – TFS
    Sep 3, 2016 at 13:31
  • check updated answer
    – Sohel Rana
    Sep 3, 2016 at 14:34
  • Thanks @SohelRana for this post. Just I want to know when remote validation called on form submit or for texchange if I have text box with this validation. I want to call this validation on text change or focus out from input is there any way to do ??? thanks in advance.
    – Manish
    Nov 7, 2016 at 6:35
  • Can I know when I get the response of this remote request I have to show loader till then? Is there a method for this event?
    – anujeet
    Mar 8, 2017 at 11:04
  • Very good ! :) @anujeet if you want to show the loader, you can add 'showLoader: true' to the remote JSON options
    – Jona
    Dec 8, 2017 at 9:20

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.