2

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?

1 Answer 1

5

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>
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.