JenkinsDev/Validatinator

Add custom regex pattern matching

Closed this issue · 3 comments

While this library has lots of good validation options, some valid field values simply don't fit neatly into one of those validation options. It would be nice to have a way to pass a RegEx string as part of a field validation configuration.
For example:

{
   ".my-field-query-selector": "required|pattern:\\d{3}[\\*_\\-][a-z]{4}",
   ...
}

This example would create a regular expression for a field value that starts with 3 numbers has one of *, _ , - and is followed by 4 lowercase letters.

Then this could be parsed in a new pattern method:

static pattern(form: HTMLFormElement, field: HTMLInputElement, regexPattern: string) {
  const regex = new RegExp(regexPattern);  
  return regex.test(field.value);
}

The double backslash is required since it is in a string. A single backslash would only create an escape sequence inside the string and would not result in a literal backslash in the constructed regular expression.

I think that’s a brilliant idea. Would you like to create a PR for this change?

I can also look at adding this sometime within the next week, otherwise

Yes I'd be happy to creat a PR for this soon. Thanks for the consideration.

Closing with merge of #30