Skip to content

Magento 2 custom validation rule in UI component form field with Ajax

I have created a custom validation rule in my admin ui form using the below link

https://webkul.com/blog/add-custom-validation-rule-in-ui-component-form-field/

If I use a direct condition then it is working fine. I need to call a ajax function and based on that response I need to validate the field. In this case it is always shows error. Not depend on the ajax response. It returns a false before completing the ajax.

Here is my js code

   require(
    [
        'Magento_Ui/js/lib/validation/validator',
        'jquery',
        'mage/translate'
], function(validator, $){
        validator.addRule(
            'prefix-exist-validation',
            function (value) {
                // if (value == 'PE') {
                //     return true;
                // }
                // return false;
                var url = BASE_URL.split('admin/')[0];
                $.ajax({
                    url:  url+"admin/abc/prefix/Validate",
                    showLoader: true,
                    data: {'group_code':value},
                    type: "POST",
                    dataType : 'json',
                    success: function(result){
                        return result.success;
                    }
                });
            },
            $.mage.__('Prefix Code already exist.')
        );
});

Please help me to fix this