2

In Regula, how can I have a constraint that does NOT match a pattern? I can use @Pattern like this:

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

But let's say that /[0-9]-[A-Z]{3}-[0-9]{4}/ is a "bad" pattern and I want to allow them to enter anything that doesn’t match that pattern.

In regular JavaScript I can do:

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

How can I do it in Regula?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Dirty Randy
  • 35
  • 1
  • 4

1 Answers1

2

There are a few ways to do this. For your case, you can use a negative lookahead:

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

I'm not sure how that works for more-complex regular expressions, but if that's the case, I guess you could create a custom constraint:

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);
    }
});

You can even defer to the inbuilt @Pattern validator in your validator function, like so:

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

Then you can use it in your input element like so:

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

I suggest the second approach because you can pass in parameters that the in-built @Pattern validator supports, like flags for regular-expression flags. This is also a proper inverse of the inbuilt validator.

EDIT: I think it might be useful to add an optional parameter to @Pattern so that you can invert the pattern. So basically (assuming this feature was implemented) all you would have to do is this:

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

I'll put this on my list of things to do.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295