【问题标题】:Check that a pattern does not match检查模式是否不匹配
【发布时间】:2013-07-16 22:37:14
【问题描述】:

Regula 中,我怎样才能有一个不匹配模式的约束?我可以像这样使用@Pattern

<input type="text" id="categoryId" data-constraints="@Pattern(regex=/[0-9]-[A-Z]{3}-[0-9]{4}/)" />

但假设/[0-9]-[A-Z]{3}-[0-9]{4}/ 是一个“坏”模式,我想让他们输入任何匹配该模式的内容。

在普通的 JavaScript 中我可以做到:

if(!/[0-9]-[A-Z]{3}-[0-9]{4}/.test(value)) {
     ...
}

如何在 Regula 中做到这一点?

【问题讨论】:

    标签: javascript regex validation regula


    【解决方案1】:

    有几种方法可以做到这一点。对于您的情况,您可以使用否定前瞻:

    <input type="text" id="categoryId" data-constraints="@Pattern(regex=/^(?!.*[0-9]-[A-Z]{3}-[0-9]{4})/)" />
    

    我不确定这对于更复杂的正则表达式是如何工作的,但如果是这种情况,我想你可以创建一个自定义约束:

    regula.custom({
        name: "NotPattern",
        params: ["regex"],
        defaultMessage: "The value must not match {regex}.",
        validator: function(params) {
            var regex = new RegExp(params["regex"]);
            return !regex.test(this.value);
        }
    });
    

    您甚至可以在验证器函数中使用内置的 @Pattern 验证器,如下所示:

    regula.custom({
        name: "NotPattern",
        params: ["regex"],
        defaultMessage: "The value must not match {regex}.",
        validator: function(params, validator) {
            return !validator.pattern(this, params);            
        }
    });
    

    然后你可以像这样在你的输入元素中使用它:

    <input type="text" id="categoryId" data-constraints="@NotPattern(regex=/[0-9]-[A-Z]{3}-[0-9]{4}/)" />
    

    我建议使用第二种方法,因为您可以传入内置 @Pattern 验证器支持的参数,例如用于正则表达式标志的 flags。这也是内置验证器的适当反转。

    编辑:我认为向@Pattern 添加一个可选参数可能会很有用,这样您就可以反转模式。所以基本上(假设这个功能已经实现)你所要做的就是:

    <input type="text" id="categoryId" data-constraints="@Pattern(regex=/[0-9]-[A-Z]{3}-[0-9]{4}/, invert=true)" />
    

    我会把这个放在我的待办事项清单上。

    【讨论】:

      猜你喜欢
      • 2012-09-17
      • 1970-01-01
      • 2017-11-30
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多