Add Custom Validation System Configuration Field
In this post we will see together how you can add a custom validation rule to a system configuration field. Is a common task that we face quite ofter so we would like to share it with you!
Adding a system configuration section in Magento 2 is a topic that we have already covered. Also using the validation tag to that field, to validate it again a rule before saving it is also well known. So let's see how you can extend the default validation rules by adding your custom one.
Below you can see a system configuration file with a text field and a custom validation rule called validate-greater-than-one. Meaning that the rule will validate out field if the value entered is greater than one.
To add our custom validation rule we will need to extend the default Magento 2 validator js using a mixin in our requirejs-config.js file like below.
Afterwards you will need to create that js file using the validator's function addMethod to add our rule like below.
Then in the backend will trying to save a value for our field if it's lower that 1 we will get the following message.
The full example as extension can be found here.
Feel free to share this post and ask your questions in the comments below.
Till next time!