caneara / iodine

A micro JavaScript validation library.
MIT License
521 stars 25 forks source link

Custom Error Messages Keys #61

Open SiCoUK opened 9 months ago

SiCoUK commented 9 months ago

This may or may not be an issue, but it's not how I was expecting it to behave!

When adding custom error messages (specifically in Single Item Checks):

a) you must provide custom messages for all validation rules.

The following returns 'undefined' for the error key of the numeric validation as there is no custom message.

Iodine.assert(field.value, ['required', 'numeric', 'minLength:2'], { 'required' : 'required.', 'minLength:2' : 'minLength.' });

Returned Object: Object { valid: false, rule: "numeric", error: undefined }

I was expecting the default message back. It would seem it might make more sense to allow the overriding of just one or two validation messages and fall back to the default if one is not provided.

b) when using params in a validation the key for the custom error message must include the parameter.

The following returns 'undefined' for the error key of the minLength validation as it is looking for minLength:2 in the messages.

Iodine.assert(field.value, ['required', 'minLength:2'], { 'required' : 'required.', 'minLength' : 'minLength.' });

Returned Object: Object { valid: false, rule: "minLength:2", error: undefined }

By specifying the parameter as the message key you get the correct message back:

Iodine.assert(field.value, ['required', 'minLength:2'], { 'required' : 'required.', 'minLength:2' : 'minLength.' });

I was expecting it to use the validation rule key as the message key and not to include the parameters as it is unlikely you would use two minLength rules on one field!

Obviously, both of these can be worked around, I just wasn't sure if it was by design. If it is by design can we add a small comment to the docs?

mattkingshott commented 9 months ago

Sorry I missed this.

It’s not by design, just how it ended up. If you want to submit a PR, then I’d be happy to merge.

FYI, I don’t really do much with Iodine these days and am considering marking it abandoned. I just don’t use it anymore.