Magento 2 – jQuery remote field validation in custom form

One of the most parts of any web application is the exchange of data. So the data must be valid and in well-defined form. Validate Magento form field is the key point here. Basically, there is two type of validation i.e client and server side validation. Client-side validation is always in the sense of providing a better User Experience (UX), so the user doesn’t have to submit and reload a page simply because a value in a form isn’t valid – it makes things more dynamic. It is trivial to edit the source of a page locally in order to disable or bypass even the most complex of JS validation.
What could a user do if you do not server-side validate?
Validation should always be performed server-side – you can never trust client-side validation.
So the server side validation is the actual validation of data. If AJAX is in the game, it is different – it allows you to save bandwidth as well as to provide the user with feedback before submission. Finally, if you’re building strictly client-side, peer-to-peer exchange apps (think games), you’ll want client-side validation to keep the clients from cheating. In this article, we are going to discuss server side form field validation using the jQuery remote method.
Now the question is what is jQuery remote validation?
Basically, it is a mechanism that can make a remote server call in order to validate a form field without posting the entire form to the server. This is useful when you have a field that cannot be validated on the client and is, therefore, likely to fail validation when the form is submitted.

How to integrate jQuery remote validation in Magento?

Let’s consider a scenario where I’m developing a custom form with a username and email that require validation at server side to check if the email exists. How can I apply the remote method of jquery with the Magento form? So the basic idea we need an ajax call and controller where ajax call hit the server to process the request.
Step 1. Create a form element for your form like

<div class="form-group">
<label>Email</label> 
<input class="form-control" name="email" type="email" data-validate="{required:true, 'validate-email':true, 
'remote':'<?php echo $this->getUrl('registration/index/validate', ['_secure' => true]); ?>'}" />
</div>

Step 2. Create controller and process validation on server side

<?php 
namespace CompanyRegistrationControllerIndex;

use MagentoFrameworkAppActionAction;

class Validate extends Action
{
 /**
 * @var MagentoFrameworkControllerResultJsonFactory
 */
 protected $resultJsonFactory;
 
 /**
 * @var MagentoCustomerModelCustomer 
 */
 protected $_customerModel;

 /**
 * @param MagentoFrameworkAppActionContext $context
 * @param MagentoFrameworkControllerResultJsonFactory $resultJsonFactory
 */
 public function __construct(
     MagentoFrameworkAppActionContext $context,
     MagentoFrameworkControllerResultJsonFactory $resultJsonFactory,
     MagentoCustomerModelCustomer $customerModel
 ) {
     $this->resultJsonFactory = $resultJsonFactory;
     $this->_customerModel = $customerModel;
     parent::__construct($context);
 }

 public function execute()
 {
     $resultJson = $this->resultJsonFactory->create();
     $email = $this->getRequest()->getParam('email');
     $customerData = $this->_customerModel->getCollection()
                   ->addFieldToFilter('email', $email);
     if(!count($customerData)) {
       $resultJson->setData('true');
     } else {
       $resultJson->setData('That email is already taken, try another one');
     }
     return $resultJson;
 }
}

Step 3. After submitting the form you will get error message like this

email-remote-validation

Conclusion

Here we have gone through the simple way to validate individual form element on the server side. We just add an attribute instead of writing a complete ajax function without any hassle of Javascript/jQuery error and save our day. By this approach, we can reduce the traffic and payload to validate form when lots of concurrent users post their data.

Reference

Magento

Jqueryvalidation.org

Leave a Comment

Scroll to Top