Validating data with Joi can result in multiple error messages being displayed for a single field

I'm attempting to implement a validation flow using the joi package, which can be found at https://www.npmjs.com/package/joi.

1) First, I want to check if the field category exists. If it doesn't, I should display the error message category required.

2) Next, I need to verify that the category field only allows alphabetic characters. If it contains any other characters, I should show the error message provide valid category

Below is my code snippet:

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')),
});

Unfortunately, the code did not work as expected.

Answer №1

If you want to identify the cause of an error, you can pass a callback function to the error() method.

Your custom callback could be structured as follows:

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');
        }
    }
}; 

After defining your callback function, you can integrate it like this:

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

Below is the entire code snippet that demonstrates the usage:

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);
        });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for utilizing jQuery to substitute strings within a content variable?

$content = "Please locate the student results where Date of birth **IS BETWEEN** 2012-02-18 00:00:00 AND 2013-02-18 00:00:00 AND name **IS NOT EQUAL TO** 'John' AND marks **IS BETWEEN** 40 AND 75 AND grade **EQUAL TO** 'A' AND AGE **I ...

Integrate the function app.createServer with app.use

I am working on developing a Nodejs application using express. My goal is to have lasting sessions with each client, while also incorporating socket.io in the future. Instead of manually parsing the request and using a switch-case statement to route it t ...

The error message "THREE is not defined" indicates a problem

Hey there! I've been experimenting with running some three.js examples on my local machine. I ran into some security issues, so I set up a local server using Python. While the background image and text appear as expected, the animations are not workin ...

Failure to give an error message occurred during a POST request on Parse.com and ExpressJS platform

I'm facing an issue where a POST request I send fails with error code 500 and there is nothing showing up in my server side error log. It seems like the cloud method may be missing. What's interesting is that the same POST request works fine wit ...

"react commands" are not recognized as an internal or external command by any program or batch file

Initially, everything was working smoothly until I decided to download some updates from the git repository. However, upon execution, I encountered an error message stating that "react scripts" are not recognized as an internal or external command, operabl ...

Tips for making a bookmark for your iframe content

Within this HTML code, there is a list element with the ID "about_ma" and an iframe named "page" that is initially hidden. <div id="navigation"> <ul id="nav"> <li id="about_ma"><a href="index1.php?name=about.php">Ab ...

Using regular expressions, you can conveniently extract text that is contained within paragraph tags

I attempted to use RegExp in JavaScript to extract text between paragraph tags, but unfortunately it isn't working... Here is my pattern: <p>(.*?)</p> The text I am trying to extract from is: <p> My content. </p> <img sr ...

Tips on displaying information following the parsing of JSON

Trying to retrieve a list of users using this code snippet <div id="users" data-users='[{"name":"one","userName":"user_one"}, {"name":"two","userName":"user_two&q ...

Issue with event binding on datepicker that is dynamically added is not functional

I have integrated the Kendo datepicker into my project, and I am facing an issue with duplicated div elements containing datepickers. The problem is that the datepicker events only fire once on the first duplicated div and then stop working altogether. I ...

Replace async/await with Promise

I want to convert the async/await code snippet below: const mongoose = require('mongoose') const supertest = require('supertest') const app = require('../app') const api = supertest(app) test("total number of blogs" ...

Is the utilization of the React context API in NextJS 13 responsible for triggering a complete app re-render on the client side

When working with NextJS 13, I've learned that providers like those utilized in the React context API can only be displayed in client components. It's also been made clear to me that components within a client component are considered part of the ...

Display only the spans that contain text or are not empty

I need a solution to hide only those spans that are empty. <div class="img-wrapper"> <div class="showcase-caption" style="display: block; "> <span id="MainContent_ImageCaption_0">This one has caption</span> </div> ...

Incorporating a Worldwide Navigation Parameter using Express 4.11

I'm currently working on setting up a global parameter for my Router in Express 4.11. The idea behind this is to use router.all('/*',function(){}); to generate a list of all routes dynamically, which I can then use to create a navigation bar ...

Utilizing JSON and select for dependency management

Let's say we have a JSON object: { "A": { "1": "1", "2": "2", "3": "3" }, "B": { "4": "4", "5": "5", "6": "6" }, "C": { "7": "7", "8": "8" } } And we also have ...

Display the names of files depending on the selection made in the drop-down menu

In order to utilize a value from a select box for a PHP function later on the page, I am seeking assistance. Within my index.php file, there is a standard select drop down containing folder names as values and options. After selecting a folder, I aim to e ...

What is the difference in memory usage for JavaScript objects between Node.js and Chrome?

It's puzzling to me why the size of the heap is twice as large as expected. I meticulously constructed a binary tree with perfection. I suspect v8 recognizes that each node consists of 3 fields. function buildTree(depth) { if (depth === 0) return n ...

Getting row data from ag-grid using the angular material menu is a straightforward process

I have a specific requirement in ag-grid where I need to implement a menu to add/edit/delete row data. Currently, I am using the angular material menu component as the cell template URL. However, I am facing an issue where when I click on the menu item, it ...

Stop jQuery Tab from Initiating Transition Effect on Current Tab

Currently, I am utilizing jQuery tabs that have a slide effect whenever you click on them. My query is: How can one prevent the slide effect from occurring on the active tab if it is clicked again? Below is the snippet of my jQUery code: $(document).read ...

express-flash-notification displays the following error message: "No default engine was specified and no extension was provided."

Recently, I started working with node.js and using MEAN stack for my project. In the footer of my project, I have an option to "Subscribe email". Due to constraints in the architecture, I am unable to utilize Angular for displaying flash messages as I don& ...

Retrieve the file by utilizing the HTML obtained from the AJAX request

Currently, I am attempting to accomplish the task of downloading a file on the same page utilizing HTML generated from an AJAX call. The AJAX call is structured as follows: $.ajax({ url: './x ...