如何使用github.com/1000hz/bootstrap-validator的自定义验证器

leo*_*leo 9 javascript plugins custom-validators

从文档http://1000hz.github.io/bootstrap-validator/:

添加要运行的自定义验证程序.验证器应该是接收jQuery元素作为参数的函数,并根据输入的有效性返回truthy或falsy值.

对象结构是: {foo: function($el) { return true || false } }

将验证器添加到输入中就像其他人一样data-foo="bar".

您还必须通过errors选项为任何自定义验证器添加默认错误消息.

我不太明白如何定义我自己的自定义验证器以及如何将它与此插件一起使用.

谁能给我一个简单的例子或提示?

jul*_*bou 12

您需要手动调用您的插件,因为custom选项不适用于数据属性:

$().validator({
    custom: {
        'odd': function($el) { return Boolean($el.val() % 2);}
    }
})
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

<input placeholder="plz enter odd value" data-odd>
Run Code Online (Sandbox Code Playgroud)

不要忘记添加错误消息,请参阅代码

  • 不再使用errors选项.如果字段无效,则验证函数应返回错误消息. (5认同)

小智 6

我想通过更多细节来充实答案.

我在尝试使用data-api(放入data-toggle="validator"表单标签)时这样做.从我的<form>标签中删除它并使用Javascript启用它,我的自定义函数工作:

$('#sign-up_area').validator({
    custom: {
        'odd': function($el) { return Boolean($el.val() % 2);}
    },
    errors: {
        odd: "That's not an odd number!"
    }
});
Run Code Online (Sandbox Code Playgroud)

我还必须为data-odd属性添加一个值:

<div class="row">
    <div class="form-group col-xs-12 col-md-12">
        <label class="control-label" for="test">Odd/Even:</label>
        <input type="text" name="test" id="test" class="form-control" placeholder="Enter an odd integer" data-odd="odd" >
        <span class="help-block with-errors"></span>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果我将以下内容添加到<input>元素中,它优先于javascript中声明的错误消息:

data-odd-error="Not an odd number, yo!"
Run Code Online (Sandbox Code Playgroud)

但是,如果我只使用data-odd-error属性但在Javascript中指定了NO错误消息,则在控制台中出现错误.因此,您必须在Javascript中声明错误消息.