During development, we collect various data from users. This data needs to be checked for correct input. Magento 2 provides built-in client-side validation tools based on jQuery Validate and Magento’s validation library.
Developers can also create custom validation rules when a project requires additional checks for customer data, checkout fields, or custom modules. Let’s consider how it’s done.
How to add validation in Magento 2
How to create a validator at the module level in Magento 2
Magento 2 validation rules
Example of validation
This is how validation looks on the registration page.
1. Connect the validator to the form.
In order for the fields inside the form to pass validation, you need to add the following attribute to the
|
1 2 |
<form /> tag: <form data-mage-init='{"validation":{}}' … > |
2. Add validation rules to the elements inside the form.
You can do this in different ways:
- declare validation rules in the data-mage-init attribute
|
1 2 3 4 5 6 7 8 9 |
<form data-mage-init='{ "validation":{ "rules": { "login": { "required":true } } } }' … > |
- add the data-validate attribute to the element
1<input type="text" data-validate='{"required":true}' name="login" id="login" ... /> - use the rule name as an attribute
1<input type="text" required="true" name="login" id="login" ... /> - use the rule name as a class
1<input type="text" class="input-text required" name="login" id="login" ... /><a id="step_2" style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 16px;"></a>

Magento Custom Development
Take your online store to the next level with BelVG Magento Custom Development
Visit the pageHow to create a validator at the module level in Magento 2
Magento 2 validation methods remain widely used in custom themes and modules, but modern Magento development also requires attention to security, accessibility, and user experience. Client-side validation should always be combined with server-side validation because browser-based checks can be bypassed.
1. Create a JS file with a custom validation rule.
Example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
app/code/<Vendor>/<Module>/view/frontend/web/js/validation.js requirejs([ 'jquery', 'jquery/ui', 'jquery/validate', 'mage/translate' ], function($){ 'use strict'; $.validator.addMethod( "ruleValidationName", function(value, element) { return false; }, $.mage.__("Your validation message") ); }); |
Add a new rule using the addMethod. The first parameter is the validator name. The second parameter is the function, the result of which is either true or false. When the function returns false, the user sees a label with the error text, which should be specified in the third parameter.
2. Connect the validator.
Depending on your goals, it can be done in different ways.
2.1 Connect JS in the layouts where the validator should be used
|
1 |
<link src="Vendor_Module::js/validation.js"/> |
Having created the validator, add it to the required element. I described how to do this in the beginning of the article.
2.2 Register the JS file in the requirejs-config.js file
Register the JavaScript file through requirejs-config.js and initialize it on the required pages or components. The exact implementation depends on whether the validator is needed globally or only in a specific module area.
Example:
|
1 2 3 4 5 6 7 8 |
app/code/<Vendor>/<Module>/view/frontend/requirejs-config.js. var config = { map: { "*": { myValidation: "<Vendor_Module>/js/validation" } } }; |
Connect the validator in the phtml file:
|
1 2 3 4 5 6 7 |
<script type="text/x-magento-init"> { "*": { "myValidation": {} } } </script> |
The created validator can be added to the required element. I described how to do this in the beginning of the article.
2.3 Validation check in custom JS
If you need to perform some other action besides the validation check, you can check the validity of the form in the JS file:
|
1 2 3 4 5 6 7 8 |
$('#btn').on('click', function() { var form = '#form'; if ($(form).validation() && $(form).validation('isValid')) { //true } else { //false } }); |
It is worth mentioning that Magento has a large number of out-of-the-box validators, so before creating your own validator, check if it has been written before.
Client-side vs server-side validation
Magento 2 developers should not rely only on JavaScript validation. Client-side checks improve user experience, but all important validation rules must also be applied on the server side. It prevents invalid or malicious data from being submitted through alternative methods such as API requests or custom scripts.
Magento 2 validation rules
Below you can find commonly used validation rules available in Magento 2. The exact list may vary between Magento versions, so always check the validation files included with your current installation.
The table has 2 columns: the first contains attribute names, and the second contains the text of the error.
1. JQuery rules
You can see the list of rules in the lib/web/jquery/jquery.validate.js file.
| required | This is a required field. |
| remote | Please fix this field. |
| Please enter a valid email address. | |
| url | Please enter a valid URL. |
| date | Please enter a valid date. |
| dateISO | Please enter a valid date (ISO). |
| number | Please enter a valid number. |
| digits | Please enter only digits. |
| creditcard | Please enter a valid credit card number. |
| equalTo | Please enter the same value again. |
| maxlength | Please enter no more than {0} characters. |
| minlength | Please enter at least {0} characters. |
| rangelength | Please enter a value between {0} and {1} characters long. |
| range | Please enter a value between {0} and {1}. |
| max | Please enter a value less than or equal to {0}. |
| min | Please enter a value greater than or equal to {0}. |
2. Magento rules.
You can see the list of rules in the lib/web/mage/validation.js file.
| max-words | Please enter {0} words or less |
| min-words | Please enter at least {0} words |
| range-words | Please enter between {0} and {1} words |
| letters-with-basic-punc | Letters or punctuation only please |
| alphanumeric | Letters, numbers, spaces or underscores only please |
| letters-only | Letters only please |
| no-whitespace | No white space please |
| zip-range | Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx |
| integer | A positive or negative non-decimal number please |
| vinUS | The specified vehicle identification number (VIN) is invalid |
| dateITA | Please enter a correct date |
| dateNL | Vul hier een geldige datum in |
| time | Please enter a valid time, between 00:00 and 23:59 |
| time12h | Please enter a valid time, between 00:00 am and 12:00 pm |
| phoneUS | Please specify a valid phone number |
| phoneUK | Please specify a valid phone number |
| mobileUK | Please specify a valid mobile number |
| stripped-min-length | Please enter at least {0} characters |
| validate-no-utf8mb4-characters | Please remove invalid characters: {0} |
| credit-card-types | Please enter a valid credit card number |
| ipv4 | Please enter a valid IP v4 address |
| ipv6 | Please enter a valid IP v6 address |
| pattern | Invalid format |
| allow-container-className | bool |
| validate-no-html-tags | HTML tags are not allowed |
| validate-select | Please select an option |
| validate-no-empty | Empty Value |
| validate-alphanum-with-spaces | Please use only letters (a-z or A-Z), numbers (0-9) or spaces only in this field |
| validate-data | Please use only letters (a-z or A-Z), numbers (0-9) or underscore (_) in this field, and the first character should be a letter |
| validate-street | Please use only letters (a-z or A-Z), numbers (0-9), spaces and “#” in this field |
| validate-phoneStrict | Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890 |
| validate-phoneLax | Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890 |
| validate-fax | Please enter a valid fax number (Ex: 123-456-7890) |
| validate-email | Please enter a valid email address (Ex: johndoe@domain.com) |
| validate-emailSender | Please enter a valid email address (Ex: johndoe@domain.com) |
| validate-password | Password requirements depend on the Magento security configuration, including minimum length and required character classes |
| validate-admin-password | Please enter 7 or more characters, using both numeric and alphabetic |
| validate-customer-password | Minimum length of this field must be equal or greater than %1 symbols. Leading and trailing spaces will be ignored.
Minimum of different classes of characters in password is %1. Classes of characters: Lower Case, Upper Case, Digits, Special Characters |
| validate-url | Please enter a valid URL. Protocol is required (http://, https:// or ftp://) |
| validate-clean-url | Please enter a valid URL. For example http://www.example.com or www.example.com |
| validate-xml-identifier | Please enter a valid XML-identifier (Ex: something_1, block5, id-4) |
| validate-ssn | Please enter a valid social security number (Ex: 123-45-6789) |
| validate-zip-us | Please enter a valid zip code (Ex: 90602 or 90602-1234) |
| validate-date-au | Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006 |
| validate-currency-dollar | Please enter a valid $ amount. For example $100.00 |
| validate-not-negative-number | Please enter a number 0 or greater in this field |
| validate-zero-or-greater | Please enter a number 0 or greater in this field |
| validate-greater-than-zero | Please enter a number greater than 0 in this field |
| validate-css-length | Please input a valid CSS-length (Ex: 100px, 77pt, 20em, .5ex or 50%) |
| validate-number | Please enter a valid number in this field |
| required-number | Please enter a valid number in this field |
| validate-number-range | The value is not within the specified range |
| validate-digits | Please enter a valid number in this field |
| validate-digits-range | The value is not within the specified range |
| validate-range | The value is not within the specified range |
| validate-alpha | Please use letters only (a-z or A-Z) in this field |
| validate-code | Please use only letters (a-z), numbers (0-9) or underscore (_) in this field, and the first character should be a letter |
| validate-alphanum | Please use only letters (a-z or A-Z) or numbers (0-9) in this field. No spaces or other characters are allowed |
| validate-date | Please enter a valid date |
| validate-date-range | Make sure the To Date is later than or the same as the From Date |
| validate-cpassword | Please make sure your passwords match |
| validate-identifier | Please enter a valid URL Key (Ex: “example-page”, “example-page.html” or “anotherlevel/example-page”) |
| validate-zip-international | Please enter a valid zip code |
| validate-one-required | Please select one of the options above |
| validate-state | Please select State/Province |
| required-file | Please select a file |
| validate-ajax-error | bool |
| validate-optional-datetime | The field isn’t complete |
| validate-required-datetime | This is a required field |
| validate-one-required-by-name | Please select one of the options |
| less-than-equals-to | Please enter a value less than or equal to %s |
| greater-than-equals-to | Please enter a value greater than or equal to %s |
| validate-emails | Please enter valid email addresses, separated by commas. For example, johndoe@domain.com, johnsmith@domain.com |
| validate-cc-type-select | Card type does not match credit card number |
| validate-cc-number | Please enter a valid credit card number |
| validate-cc-type | Credit card number does not match credit card type |
| validate-cc-exp | Incorrect credit card expiration date |
| validate-cc-cvn | Please enter a valid credit card verification number |
| validate-cc-ukss | Please enter the issue number or the start date for the switch/solo card type |
| validate-length | Please enter less or equal than %1 symbols..replace(‘%1’, length);
Please enter more or equal than %1 symbols..replace(‘%1’, length) |
| required-entry | This is a required field |
| not-negative-amount | Please enter a positive number in this field |
| validate-per-page-value-list | Please enter a valid value, ex: 10,20,30 |
| validate-per-page-value | Please enter a valid value from the list |
| validate-new-password | Please enter 6 or more characters. Leading and trailing spaces will be ignored |
| required-if-not-specified | This is a required field |
| required-if-all-sku-empty-and-file-not-loaded | Please enter a valid SKU key |
| required-if-specified | This is a required field |
| required-number-if-specified | Please enter a valid number |
| datetime-validation | This is a required field |
| required-text-swatch-entry | Admin is a required field in each row |
| required-visual-swatch-entry | Admin is a required field in each row |
| required-dropdown-attribute-entry | Admin is a required field in each row |
| validate-item-quantity | Please enter a quantity greater than 0;
The fewest you may purchase is %1; The maximum you may purchase is %1; You can buy this product only in quantities of %1 at a time |
| password-not-equal-to-user-name | password-not-equal-to-user-nam |
Magento validation remains an important part of creating secure and user-friendly ecommerce experiences. When developing custom Magento 2 functionality, developers should regularly review validation rules and ensure they adhere to current security practices and platform updates.
This is all for this topic! I hope my article was useful to you. If you have a question or want to add something, feel free to leave us a comment down below.
Looking for quality Magento 2 extensions? Visit our webstore and find the tools to help you run your ecommerce.

Extensions for Magento 2
Take your online store to the next level with BelVG extensions
Visit the page

