Steps for Magento 2 custom form validation

Form validation in Magento 2 plays a vital role in ensuring that only accurate, properly formatted, and secure information is submitted through your store’s forms. Without it, your site could be exposed to spam submissions, malicious inputs, or poorly formatted customer data that creates inefficiencies in your store operations.

Magento 2 uses both client-side validation (to provide immediate feedback to users) and server-side validation (to act as the final security checkpoint). Together, these layers protect your store and improve user experience.

In this article, we’ll explore how Magento 2 form validation works, how to create custom rules, and walk through a step-by-step implementation guide.

Key Takeaways

  • Magento 2 supports client-side and server-side validation for accuracy and security.

  • Developers can apply rules using HTML attributes, CSS classes, or data-validate attributes.

  • Magento provides a large set of built-in rules, but also supports custom validation for specific use cases.

  • Custom error messages improve clarity and user experience.

  • Proper validation ensures clean data, better UX, stronger security, and reduced server overhead.

Understanding Magento 2 Validation

Magento’s validation system works on two levels:

Client-Side Validation

  • Provides instant feedback as users fill out forms.

  • Built on the jQuery Validation plugin, extended with Magento’s own validation module.

  • Rules can be applied via:

    • data-validate attribute → data-validate='{"required":true, "validate-email":true}'

    • Class names → class="input-text required validate-email"

    • Direct HTML attributes → required="true"

  • Prevents invalid form submissions, improving UX and reducing unnecessary server requests.

Server-Side Validation

  • Works as the final checkpoint before saving or processing data.

  • Ensures malicious or incorrect submissions don’t bypass client-side validation.

  • Typically implemented within controllers or models in Magento 2.

Both layers together maintain data accuracy, system security, and smooth customer experience.

How to Create Magento 2 Custom Form Validation?

Now, let’s go step by step and create a custom validation rule in Magento 2.

Step 1. Add the data-mage-init Attribute to the Form Tag

First of all, we need to add “data-mage-init” attribute with “validation” alias in your form using the code below.

<form class="form my-form" action="" method="post" data-mage-init='{"validation":{}}'>
    //Form code
</form>

This triggers Magento’s validation.js (located in lib/web/mage/validation/validation.js), which contains the logic for form validation.

Step 2. Add Validation Rules to Input Fields (4 Methods)

Next, we need to add a validation rule in input fields.

Now, there are a total of 4 methods to add validation rules in the input fields of a form in Magento 2.

Method 1. Use Rule Name As an Attribute

<input required="true" name="field" type="text" />

Method 2. Use Rule Name As Class Name

<input class="input-text required" name="field" type="text" />

Method 3. Use “Data-Validate” Attribute

<input data-validate='{"required":true}' name="field" type="text" />

Method 4. Set Rule in data-mage-init Attribute of Form Tag

<form class="form my-form" action="" method="post" data-mage-init='{
    "validation":{
        "rules": {
            "fieldname": {
                "required":true
            }
        }
    }
}'>

And that’s it! This is how you can validate forms in Magento 2.

Custom Validation Rules and Messages

For unique business needs, Magento allows developers to extend validation:

  • Custom Rules: Define validation logic using JavaScript.

  • Custom Error Messages: Override default error messages for better user guidance.

Example: Restricting usernames to only letters and numbers:

$.validator.addMethod(
  "validate-username",
  function(value) {
    return /^[a-zA-Z0-9]+$/.test(value);
  },
  "Username must contain only letters and numbers."
);

Usage:

<input data-validate='{"validate-username":true}' name="username" />

Bonus: Complete List of Magento 2 Validation Rules

  • range-words
  • letters-with-basic-punc
  • alphanumeric
  • letters-only
  • no-whitespace
  • max-words
  • min-words
  • zip-range
  • integer
  • vinUS
  • dateITA
  • dateNL
  • time
  • time12h
  • phoneUS
  • phoneUK
  • mobileUK
  • stripped-min-length
  • email2
  • url2
  • credit-card-types
  • ipv4
  • ipv6
  • pattern
  • allow-container-className
  • less-than-equals-to
  • greater-than-equals-to
  • validate-emails
  • validate-cc-type-select
  • validate-cc-number
  • validate-cc-type
  • validate-cc-exp
  • validate-cc-cvn
  • validate-cc-ukss
  • validate-length
  • required-entry
  • not-negative-amount
  • validate-per-page-value-list
  • validate-per-page-value
  • validate-new-password
  • required-if-not-specified
  • required-if-all-sku-empty-and-file-not-loaded
  • required-if-specified
  • required-number-if-specified
  • datetime-validation
  • required-text-swatch-entry
  • required-visual-swatch-entry
  • required-dropdown-attribute-entry
  • Validate-item-quantity
  • validate-grouped-qty
  • validate-one-checkbox-required-by-name
  • validate-date-between
  • validate-dob
  • validate-no-html-tags
  • validate-select
  • validate-no-empty
  • validate-alphanum-with-spaces
  • validate-data
  • validate-street
  • validate-phoneStrict
  • validate-phoneLax
  • validate-fax
  • validate-email
  • validate-emailSender
  • validate-password
  • validate-admin-password
  • validate-customer-password
  • validate-url
  • validate-clean-url
  • validate-xml-identifier
  • validate-ssn
  • validate-zip-us
  • validate-date-au
  • validate-currency-dollar
  • validate-not-negative-number
  • validate-zero-or-greater
  • validate-greater-than-zero
  • validate-css-length
  • validate-number
  • required-number
  • validate-number-range
  • validate-digits
  • validate-digits-range
  • validate-range
  • validate-alpha
  • validate-code
  • validate-alphanum
  • validate-date
  • validate-date-range
  • validate-cpassword
  • validate-identifier
  • validate-zip-international
  • validate-one-required
  • validate-state
  • required-file
  • validate-ajax-error
  • validate-optional-datetime
  • validate-required-datetime
  • validate-one-required-by-name

Benefits of Form Validation in Magento 2

  • ✅ Improved Data Quality: Ensures clean, accurate submissions.

  • ✅ Enhanced User Experience: Provides real-time guidance.

  • ✅ Increased Security: Blocks malicious inputs.

  • ✅ Optimized Performance: Reduces server load.

Conclusion

Form validation in Magento 2 is an essential practice to safeguard your data, enhance user trust, and streamline the shopping experience. By combining Magento’s built-in rules with custom validations, you can ensure that every submission is clean, accurate, and secure.

If you’d like to create advanced forms without coding, we recommend checking out the Magento 2 Custom Form Builder Extension — a powerful tool to build and validate forms with ease.

And if you need our professional assistance with Magento 2 Developer, feel free to reach out to us anytime.

Recommended: Magento 2 Custom Form Builder to Create Custom Form