Form Validation with Custom Error Placement

Validating a form and you want to display an element validation error message on a specific place? Then the errorPlacement function is what you need to use to achieve that. Let's see together how!

The function errorPlacement is a function of the mage.validation widget in Magento 2 and can be found under

vendor/magento/magento2-base/lib/web/mage/validation.js

Having a deeper look at the declaration of the function errorPlacement, we could see that there is already a logic implemented for displaying a validation error message on a different place depending on the element type. By default the error message is displayed on a div element below the validated element.  Below you can see the default declaration of the errorPlacement function. 

For this post we will use as an example the contact form. The contact form template can be found under

/vendor/magento/module-contact/view/frontend/templates/form.phtml

You can easily override this template by creating a template file called form.phtml under your theme folder like

app/design/frontend/Your_Theme/default/Magento_Contact/templates/form.phtml

So first of all we have to define the custom error placement. We do that by adding on the place we want, an empty div element with an id like

<div id="custom-error-message-container"></div>

Aftewards at the end of our template we need to add the following javascript code which adds our custom logic for the error placement of the element email. The result will be that the validation error message of the element email will be display on the div element that we defined above.

Our custom contact form template can be found here.

Feel free to share this post and ask your questions in the comments below.

Till next time!

DigitalOcean Referral Badge