Pristine icon indicating copy to clipboard operation
Pristine copied to clipboard

ability to add defaults to custom validator message

Open lukemcd opened this issue 5 years ago • 1 comments

I have set up a zip code validator with a custom validation error message. I would like to be able to have a default validation error message in case a custom message is not used.

Currently the element looks like this: <input type="text" data-pristine-required-message="The zip code field is required" data-pristine-zip-code="true,Please enter a valid US zip code" required>

And in the JS code:

Pristine.addValidator('zip-code', function (value, mode) {
    let pattern;
    // see if we are just checking for 5 digit zip
    if (mode == 'strict') pattern = /^[0-9]{5}?$/;
    // otherwise zip+4
    else pattern = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
    return pattern.test(value);
}, '${2}', 5, false);

This works. But I would also like to support instances where the element does not pass the error message as a second parameter: <input type="text" data-pristine-required-message="The zip code field is required" data-pristine-zip-code="true" required>

The code would fill in a default value. Something that works like a template literal:

Pristine.addValidator('zip-code', function (value, mode) {
    let pattern;
    // see if we are just checking for 5 digit zip
    if (mode == 'strict') pattern = /^[0-9]{5}?$/;
    // otherwise zip+4
    else pattern = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
    return pattern.test(value);
}, "${2 || 'Please enter a valid US zip code'}", 5, false);

This does not work. Is there a method for doing this within the current code?

lukemcd avatar Aug 05 '20 14:08 lukemcd

The message parameter can also be a function (as of 0.1.7). So I guess you can make use of it for this purpose.

sha256 avatar Aug 17 '20 17:08 sha256