简体   繁体   English

在 Parsley.js 中运行自定义验证器

[英]Running Custom Validator in Parsley.js

I've defined a number of custom Parsley validators such as:我已经定义了许多自定义 Parsley 验证器,例如:

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:当在输入上使用 HTML 标签 data-parsley-example 时,此验证按预期工作,例如:

<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:以下似乎有效,但使用私有_validatorRegistry:

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

This is similar to How do I call a built-in parsley validator from javascript?这类似于How do I call a built-in parsley validator from javascript? but the recommended solutions don't appear to work for me.但推荐的解决方案似乎对我不起作用。

There is no API or it, but you can call it on virtual DOM, eg没有 API 或它,但你可以在虚拟 DOM 上调用它,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM