Running Custom Validator in Parsley.js

339 views Asked by At

I've defined a number of custom Parsley validators such as:

Parsley.addValidator('example', {
    validateString: function(value, id=0) {
        var max_length = 25
        var regex = /^[A-Z][a-z]+$/
        if (value.length > max_length) {
            return $.Deferred().reject(`Example <b>${value}</b> is longer than ${max_length} characters.`);
        }
        if (!regex.test(value)) {
            return $.Deferred().reject(`Example <b>${value}</b> must match regex <b>${regex}</b>.`);
        }
        return $.ajax({
            type: "GET",
            url: "/rest/api/example",
            data: {
                ratio: value
            },
            dataType: 'json'
        }).then(function(response) {
            if (!response) {
                return $.Deferred().reject("There was an error retrieving example.");
            }
            if (response.length > 0) {
                if ((id <= 0) || (response[0].id != id)) {
                    return $.Deferred().reject(`Example<b>${value}</b> is already in use.`);
                }
            }
        })
    }
});

This validation works as expected when using the HTML tag data-parsley-example on an input such as:

<input type="text" class="input" id="example" placeholder="Example" data-parsley-trigger="change" data-parsley-example="">

Is there a supported way to run this validation check in a standalone method? The following seems to work but uses the private _validatorRegistry:

Parsley._validatorRegistry["validators"].example.validate(value)

This is similar to How do I call a built-in parsley validator from javascript? but the recommended solutions don't appear to work for me.

1

There are 1 answers

0
Marc-André Lafortune On

There is no API or it, but you can call it on virtual DOM, e.g.

$('<input data-parsley-example="">')
.parsley()
.whenValid({value})
.then(result => {...})