icebob/fastest-validator

Pass in objects as an error message

toms opened this issue · 1 comments

toms commented

I think it'd be cool to pass in an object as an error message that can be parsed and processed later in whatever validation function you have setup.

For example, in my use case I'd like to notify a client with a message on invalid input, but only for specific fields. Otherwise, I'd like to send a default error message. Now this can be done by manually filling each message for any potential errors, while also including the default message

someNumField: {
    type: 'number',
    integer: true,
    min: 1,
    max: 10000,
    messages: {
        number: 'Please contact support',
        integer: 'Please contact support',
        numberMin: 'Your number amount must be at least 1',
        numberMax: 'Your number must be below 10,000',
        required: 'Please contact support',
    },
},

and always just send the .message property, but I think this is unnecessarily repetitive, especially for fields with a lot of validators.

Ideally, I'd like to only specify messages for fields that I'd like to customize:

someNumField: {
    type: 'number',
    integer: true,
    min: 1,
    max: 1000000,
    messages: {
        numberMin: { isCustom: true, 'Your number amount must be at least 1' },
        numberMax: { isCustom: true, 'Your number must be below 10,000' },
    },
},

and then assign a default output message in my validator utility function:

const errorMessage = error?.message?.isCustom || 'Please contact support';

However, all objects get parsed to strings ([Object object]).
Attempting to JSON.stringify an object just leads to errors due to unescaped quotations:

undefined:8
errors.push({ type: "number", message: "{"message":"test message"}", field: field, actual: origValue, label: label });
                                          ^^^^^^^

SyntaxError: Unexpected identifier
    at new Function (<anonymous>)

A different possible solution for this scenario would be to implement a default global error message field, but I think adding in object support for messages adds some additional flexibility for other potential use cases.

I fear I don't understand your issue. You don't need to define all messages in all fields, just what you want to override.