How to Add Custom JS Validation Rule in Magento 2

How to Add Custom JS Validation Rule in Magento 2

E-commerce stores that offer their products or services to limited customers or based on specific conditions require to set validations before agreeing to serve them.

As the default Magento 2 does not offer such custom validations, I’ve come up with a method to add custom JS validation rule in Magento 2.

For example, while asking contact details from the customers, you do not want spam or fake data from unwanted users. These users are just there to spam you and processing their data is a waste of time and money.

So you can set custom validations like the correct format of email addresses, or the contact number of the specific country only to be accepted.

Doing so, you can eliminate the fake details or stop the users that you do not wish to serve. This method is also useful if you are a Magento 2 store for the local customer base only! The below solution allows you to validate the zip code at the checkout page.

Examples of validation:

Customer login

How to Add Custom JS Validation Rule in Magento 2 1

Customer Registration

How to Add Custom JS Validation Rule in Magento 2 2

Method to add custom JS validation rule in Magento 2:

Add requirejs-config.js file to the following location:

app/code/[Vendor]/[Module]/view/frontend/requirejs-config.js

Copy file  vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js

to

app/code/[Vendor]/[Module]/view/frontend/web/js/lib/validation/rules.js

Where you can add the custom validation code as following:

That’s it.

You can refer the method to override JS file in Magento 2 for easy implementation.

Any doubts? If so, do not hesitate to mention them in the Comments section below.

I’ll help you out asap.

Also, please share the solution with fellow Magento developers via social media.

Thank you.

Related Articles:

Get Weekly Updates

Never miss Magento tips, tricks, tutorials, and news.

Thank you for subscribing.

Something went wrong.

5
(based on 12 Reviews)

He is a senior Magento Developer at Meetanshi with an aim to serve the best to the store owners. In his free time, he loves to consume digital content with the family.

Leave a reply:

Your email address will not be published.