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?
asked Sep 1, 2016 at 17:00
fotfs
4,37917 gold badges48 silver badges76 bronze badges
1 Answer 1
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;
}
}
answered Sep 1, 2016 at 18:06
Sohel Rana
36.2k3 gold badges74 silver badges94 bronze badges
-
I make a controller to handle the validation.
public function execute() { return true; }It returnsInvalid return typefotfs– fotfs2016年09月03日 13:31:38 +00:00Commented Sep 3, 2016 at 13:31 -
check updated answerSohel Rana– Sohel Rana2016年09月03日 14:34:55 +00:00Commented 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– Manish2016年11月07日 06:35:19 +00:00Commented 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– anujeet2017年03月08日 11:04:38 +00:00Commented 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 optionsJona– Jona2017年12月08日 09:20:10 +00:00Commented Dec 8, 2017 at 9:20
default