【问题标题】:Running Custom Validator in Parsley.js在 Parsley.js 中运行自定义验证器
【发布时间】:2021-12-29 22:10:03
【问题描述】:

我已经定义了许多自定义 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.`);
                }
            }
        })
    }
});

当在输入上使用 HTML 标记 data-parsley-example 时,此验证按预期工作,例如:

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

是否有受支持的方式以独立方法运行此验证检查?以下似乎可行,但使用私有 _validatorRegistry:

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

这类似于How do I call a built-in parsley validator from javascript?,但推荐的解决方案似乎对我不起作用。

【问题讨论】:

    标签: javascript jquery parsley.js


    【解决方案1】:

    没有API或它,但你可以在虚拟DOM上调用它,例如

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多