- DOC | Magento 2 -


Form Validators #back to top

The instructions bellow will help you to create a custom validation to your forms

1. Create your validation rule - custom-validators.js

                                    define([
                                        'jquery',
                                        'jquery/validate',
                                        'mage/translate'
                                    ], function ($) {
                                        'use strict';

                                        $.validator.addMethod('custom-validator', function(value, element, option) {
                                            return (+value === 42);
                                        }, $.mage.__('This field must be equal to 42.'));

                                        return true;
                                    });
                                

First of all you need to import jQuery and jQuery Validate (lines 2 and 3) to be able to add a new method.

The addMethod function accepts 3 parameters. The first is the validation name, that you will use to call it on html. The second parameter is a callback that is executed when the form send the submit event. You can receive 3 values in this callback, the field value, the element with the validation and the option value that was specified on html (See the step 4, in our case the option was "true"). In this callback you can return true or false, being that false will stop the submit event and return your custom message to user. The last parameter of addMethod is a custom message that is used when your validation return false.

2. Add an alias to your model (Not required) - requirejs-config.js

                                    var config = {
                                        map: {
                                            '*': {
                                                'import-validators': 'Webjump_Doc/js/model/custom-validators'
                                            }
                                        }
                                    };
                                

You can create an alias to your model.js creating a requirejs-config.js on your module. However, this is not a required step, you can use the full path instead, but this configuration is highly recommended

3. Create the bind to your form - validators.phtml

                                    
                                

The third step is add the code above in your form container (.phtml) to create a bind with your model.js. The line 23 is your container that you want to use your validation (You can put any css selector here). You need to put your model alias here or the full path to Magento load your .js file.

4. Add your new validator to your field - validators.phtml

                                    

Finally you need to add the data-validate with your custom validator name in your field and your validator is configured.