shamon shamsudeen
shamon shamsudeen

Reputation: 5848

Joi validations: multiple validation error messages for single field

I am trying to achieve the following validation flow through joi https://www.npmjs.com/package/joi package.

1) Check the field category exists if not display the error category required.

2)Check the category field allows only alphabets if not display the error message provide valid category

Here is my code

const schema = Joi.object().keys({
    category: Joi.string().required().error(new Error('category is required')),
    category: Joi.string().regex(/^[a-zA-Z]*$/).required().error(new Error('category is not valid')),
});

But it didn't work as expected

Upvotes: 2

Views: 1844

Answers (1)

Anand Undavia
Anand Undavia

Reputation: 3543

You can actually provide a callback to the error() function and check what caused the error.

The callback in your case would look like:

const onError = x => {
    switch (x[0].type) {
        case 'any.required': {
            return new Error('category is required');
        }
        case 'string.regex.base': {
            return new Error('category is not valid');
        }
        default: {
            return new Error('category has some error');
        }
    }
}; 

Then you can use it like so:

category: Joi.string()
        .regex(/^[a-zA-Z]*$/)
        .required()
        .error(onError)

Here is the complete snippet I used:

const Joi = require('joi');

const onError = x => {
    switch (x[0].type) {
        case 'any.required': {
            return new Error('category is required');
        }
        case 'string.regex.base': {
            return new Error('category is not valid');
        }
        default: {
            return new Error('category has some error');
        }
    }
};

const schema = Joi.object().keys({
    category: Joi.string()
        .regex(/^[a-zA-Z]*$/)
        .required()
        .error(onError)
});

const testCategories = [{ category: 'ABCD' }, {}, { category: '&&&' }];

testCategories.forEach(aCategory => {
    schema
        .validate(aCategory)
        .then(() => {
            console.log(JSON.stringify(aCategory), 'passed!');
        })
        .catch(e => {
            console.log(JSON.stringify(aCategory), 'failed', e);
        });
});

Upvotes: 4

Related Questions