Magento 2 provides custom form validation messages in multiple ways. It can be easily customized by altering the validator using a simple jQuery code. By default, Magneto provides data validation rules by using this data-validate attribute.

If you’re using Magento and need to create a custom form with personalized validation messages then this blog is for you.

How To Improve Input Validation in Magento 2 with Custom Messages?

Are you frustrated by users entering invalid details, such as numbers in name fields or text in numeric fields? Don’t worry—Magento 2 provides a simple way to ensure data accuracy with custom validation messages. By implementing custom validations, you can guide your users to input valid data and improve their experience on your site.

Magento 2 provides a robust mechanism to validate form fields through the data-validate attribute. This attribute allows developers to specify validation rules directly within the form element, making it simple to enforce validation and provide custom error messages.

Let’s explore how to use “Data Validate” for validation and customize error messages for a better user experience.

Understanding Magento 2 Validation

Benefits of Custom Validation

  • Improved Data Accuracy: Reduce errors in customer information.
  • Enhanced User Experience: Prompt users with clear, helpful error messages.
  • Seamless Frontend Integration: Display messages directly on forms.

Understanding `data-validate`

The data-validate attribute is a JSON-like structure that defines the validation rules for a specific input field. You can specify multiple rules such as:

  • Required: Ensures the field is not empty.
  • Validate-email: Validates the email format.
  • Min-length, max-length: Enforces character length constraints.
  • Validate-digits, validate-number: Validates numeric input.

Each rule can have a corresponding error message defined using additional data-msg-* attributes.

Example: Validating an Email Field

<form id="contact-us-form" class="contact-us"
      data-mage-init='{"validation":{}}'
      enctype="multipart/form-data" method="post" name="contact-us">
    <fieldset class="fieldset">
        <div class="field required">
            <label class="email-label" for="email">E-mail</label>
            <div class="control">
                <input type="email" id="email" name="email" class="input-text" 
                       data-validate="{'required':true, 'validate-email':true}" 
                       data-msg-required="Please enter your email address, this field is required to proceed." 
                       data-msg-validate-email="The email address you entered in a form or field is not formatted correctly."
                       aria-required="true">
                <input type="submit" name="submit">
            </div>
        </div>
    </fieldset>
</form>

Key Components in the Example

Validation Rules (data-validate) 

  • ‘required’:true: Ensures the field is filled.
  • ‘validate-email’:true: Checks the format of the email input.

Custom Messages (data-msg-*)

  • data-msg-required: Custom message displayed when the field is empty.
  • data-msg-validate-email: Message shown when the email format is invalid.

Attributes for Accessibility

  • aria-required=”true”: Indicates to screen readers that the field is mandatory.

How Does It Work?

When the form is submitted, Magento’s JavaScript validation library (mage/validation) processes the data-validate attributes.

If the validation fails, the corresponding error message (from data-msg-*) is displayed.

This approach eliminates the need for additional JavaScript code for basic validations.

Improve Input Validation in Magento 2 with Custom Messages Using a Custom Rule

1. Create a requirejs-config.js file in your module at the following path. 

Path : app/code/<CompanyName>/<ModuleName>/view/frontend/requirejs-config.js

The requirejs-config.js file is used to configure JavaScript dependencies, and aliases, or to define new paths for modules.

var config = {
    config: {
        mixins: {
            'mage/validation': {
                '<CompanyName>_<ModuleName>/js/validator-rules-mixin': true
            }
        }
    }
};

2. Create a validator-mixin.js file in your module’s web folder

Path : app/code/<CompanyName>/<ModuleName>/view/frontend/web/js/validator-mixin.js

This ensures that the mixin is applied to mage/validation.

define(['jquery'], function($) {
  'use strict';
  return function(targetWidget) {
    $.validator.addMethod(
      'validate-five-words',
      function(value, element) {
        if(value.split(' ').length == 5){
            return true;
        }
      },
      $.mage.__('Please enter exactly five words')
    )
    return targetWidget;
  }
});

3. Create a .phtml file.

Add the data-validate attribute in your .phtml file or a UI component to use this custom validation method in a form field.
Example.phtml file:

<form id="contact-us-form" class="contact-us"
      data-mage-init='{"validation":{}}'
      enctype="multipart/form-data" method="post" name="contact-us">
    <fieldset class="fieldset">
        <div class="field required">
            <label class="name-label" for="name">Name</label>
            <div class="control">
                <input type="text" id="name" name="name" class="input-text" data-validate='{"required":true, "validate-five-words":true}'
                       aria-required="true">
                <input type="submit" name="submit">
            </div>
        </div>
    </fieldset>
</form>

Example in a UI Component (form)
In your module’s form XML or ui_component file:

<item name="validation" xsi:type="array">
    <item name="validate-five-words" xsi:type="boolean">true</item>
</item>

Benefits of Using data-validate

  • Ease of Implementation: Simple, declarative validation directly in the HTML.
  • Customizable Messages: Allows developers to provide user-friendly error messages.
  • Scalability: Supports multiple validation rules without extensive coding.
  • Integration: Works seamlessly with Magento 2’s default validation library.

Conclusion

The data-validate attribute in Magento 2 offers a powerful way to enforce input validation and display customized error messages. By utilizing this feature, you can improve the user experience and ensure data integrity with minimal effort.

At Klizer, we can help you customize validation messages with the help of our Magento 2 Experts. If you need assistance implementing advanced features like this or optimizing your Magento store, feel free to reach out to us.

Picture of Vrajesh Patel

Vrajesh Patel

Vrajesh Patel is a skilled and passionate Magento Developer at Klizer (DCKAP) with a proven track record of creating exceptional and innovative ecommerce solutions. With over 5 years of experience in the field and a commitment to continuous learning, he excels in exploring the latest advancements and remains dedicated to delivering exceptional solutions.

Get Expert Advice

At Klizer, we bring over 18 years of specialized expertise in ecommerce website development and design.

© Copyright 2024 Klizer. All Rights Reserved

Scroll to Top