cferdinandi / validate

A lightweight form validation script.
MIT License
230 stars 39 forks source link

Custom message per input #37

Closed haveanicerepo closed 6 years ago

haveanicerepo commented 6 years ago

Hi there!

I'm replacing the standard form validation in my company, and this seems like a great fit! There's one thing i'm unsure about though: custom and/or variable error messages per input. Often we use messages like "You need to fill out your last name" for example. "last name" here is variable, it only holds true for 1 particular field. I tried doing something like this:

beforeShowError: function (field, error) {
    // error would be "You need to fill out your {label}"
    error.replace('{label}', field.getAttribute('data-label'));
}

But it didn't change the error message. In fact, I can't seem to change the error message at all in the event callbacks. I think the problem is the fact that you don't know what error 'type' is going to show. What I did now is add this for each error type in the hasError function:

// If too short
if (validity.tooShort) {
    if (field.getAttribute('data-error-tooshort')) {
        return field.getAttribute('data-error-tooshort');
    } else {
        return localSettings.messageTooShort.replace('{minLength}', field.getAttribute('minLength')).replace('{length}', field.value.length);
    }
}

But it feels a bit hacky, is there some way of adding it into event callbacks?

Thank you!

cferdinandi commented 6 years ago

To be perfectly candid, a more robust plugin might better fit your needs here.

Validate.js is really intended to lightly augment native HTML5 form validation rather than provide a robust and fine-tuned level of control.

As in, what you're trying to do would be easy with some other plugins, but isn't with mine (on purpose).