Magento 2 Admin Form – Custom Validation Guide

magento-2.1

I have a custom form in admin.

And this is one of my form field

    $fieldset->addField(
        'price_coefficient',
        'text',
        [   'name' => 'price_coefficient', 
            'label' => __('Price Coefficient'), 
            'title' => __('Price Coefficient'),
            'validation' => ['validate-price-coefficient' => true],
            'note' => 'Absolute figure (+8,-3), percentage (+15%, -20%) or Currency rate (1.44)'
        ]
    );

Now I want to add validation to this field with below regular expression.

      value.match(/^[+-]?\d+[.]?\d*[%]?$/g);

How this can be done in Magento 2?

Best Answer

Add a custom class validate-my-value to your field and then add below script to your form.

<script type="text/javascript">
require([
    'jquery',
    'jquery/ui', 
    'jquery/validate',
    'mage/translate'
], function($){ 
    $.validator.addMethod(
        'validate-my-value', function (value) { 
            return value.match(/^[+-]?\d+[.]?\d*[%]?$/g);
         }, $.mage.__('Enter Valid Value')
    );
});
</script>
Related Topic