Intentionally introduce discrepancies in the errors during validation of an object using hapi/joi

const validationSchema = Joi.object().keys({
              Id: Joi.number().required(),
              CustomerName: Joi.string()
                .trim()
                .required()
                .when('$isInValidCustomer', {
                  is: true,
                  then: //Inject additional error in the existing error block for CustomerName,
                }),
               BankName: Joi.string().trim().required(),
            });

const customerDetails = {
Id: 2,
CustomerName: 'xyz'
BankName: ''
};

const schemaOptions = {
              abortEarly: false,
              context: {
                isInValidCustomer: true,
              },
            };

const validationErrors = validationSchema.validate(customerDetails, schemaOptions);

When validating the 'customerDetails' object, I need to ensure the following 2 errors occur: - An error for CustomerName due to 'isInValidCustomer' being true - An error for BankName as it is required

I'm struggling to add an error for CustomerName within the current error object. Using '.error()' only provides a single error related to either 'CustomerName' or 'BankName.'

Any assistance on this matter would be greatly appreciated.

Answer №1

One way to accomplish this is by utilizing a specialized function.

const schema = Joi.object().keys({
              Id: Joi.number().required(),
              CustomerName: Joi.string()
                .trim()
                .required()
                .when('$isInValidCustomer', {
                  is: true,
                  then: Joi.any().custom(() => {
                    throw new Error('Invalid Customer');
                    }),
                }),
               BankName: Joi.string().trim(),
            });

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

When I close all of my tabs or the browser, I aim to clear the local storage

Could you recommend any strategies for clearing local storage upon closing the last tab or browser? I have attempted to use local storage and session storage to keep track of open and closed sessions in an array stored in local storage. However, this meth ...

Turn off all VuetifyJS transitions

Is there a way to completely turn off all transitions, such as the slide-x-transition or dialog modal scale transition, in VuetifyJS? ...

CORS headers not functioning as expected for Access-Control-Allow-Origin

Can someone help me figure out how to add Access-Control-Allow-Origin: 'http://localhost:8080' in Node.js and Express.js? I keep getting this CORS error: Access to XMLHttpRequest at http://localhost:3000 from origin 'http://localhost:8080&ap ...

Embed a partial view within a Jquery modal dialogue box featuring two distinct models

I am working on a room-booking project. In my View, I have a model of rooms that displays the room ID and its characteristics using a foreach loop: @model IEnumerable<Room> <div class="roomConteiner"> @foreach (Room room in Model) ...

Looking to extract data from a Json object and add it into a table

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayJsonData() { var jsonData = { "cars": [ '{"model":"Sentra", "doors":4, "features":["hi"," ...

Double invocation of useEffect causing issues in a TypeScript app built with Next.js

My useEffect function is set up with brackets as shown below: useEffect(() => { console.log('hello') getTransactions() }, []) Surprisingly, when I run my app, it logs "hello" twice in the console. Any thoughts on why this might be ...

KnockoutJS - Using containerless control flow binding with predefined values

Inside a select control, I am using ko:foreach instead of the usual bindings. Everything is working perfectly, except that the initial value for "specialProperty" is set to unknown even when the select control is set to Option 1. It behaves as expected o ...

Adjust the color according to the key's value in every object within the array

Issue: I am faced with an array of objects, each containing a Name key. At times, the names may be repeated. I want to maintain the same color when the name is the same and switch to a different color when the name changes. Specifically, I want to alternat ...

All file upload requests consistently result in a status code of 400

I am encountering an issue with file uploading in Express. Every time I send a request with multipart/form-data, I receive a 400 bad request response with no error message, just an empty object. Currently, I am using busboy-body-parser for parsing multipar ...

"Utilize Vuejs to establish a binding between two objects when necessary

With the help of moment, my calendar generates 41 days. for (let x = 0; x < 42; x++) { context.add(1, 'd'); let day = { 'date': moment(context), 'events': [] }; } ...

Is there a way to adjust the contents of an iframe to match the dimensions of the iframe itself?

I am trying to adjust the width of an iframe to 60%, regardless of its height. Is there a way to "zoom in" on the contents of the iframe to fit the width, so that I can then set the height based on this zoom level? I haven't been able to find any solu ...

Installation of the Create React Native app was unsuccessful

After hearing about Create React Native App being the simplest way to start a new React Native application, I decided to install it. However, my attempt was unsuccessful. My Node version is v8.10.0 and npm version is v4.2.0. I encountered an error which h ...

Apply a chosen style to the element that was clicked on, while removing the style from the rest

Here is an example of my ul li structure: <div id="categoryTree"> <ul> <li id="cat_15"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">N ...

Facing issues with Angular2 integration with Semantic UI

I am currently working with Angular2 and Nodejs. Within my application, I have a list of employees that includes their names, addresses, ranks, and other details. My goal is to display additional information when a user hovers over an employee's name. ...

Having trouble updating a specific document in my MongoDB collection

I am facing an issue with my function that reads data from the database. I am trying to change the value of the "hasVoted" field in my Voters model from false to true, but it is not reflecting in the database. Even after setting data.hasVoted = true and c ...

Storing files in DynamoDB using Reactjs is a convenient and efficient way

Is there a way to store resume files in an existing DynamoDB table that currently stores name and email information? I have attempted to do so using React's AWS package with the following code: <input name="my_file" onChange={e => upd ...

I'm interested in knowing if it's feasible to develop unique jQuery selectors that can navigate ancestors, such as a :closest or :parents selector

As a developer who frequently creates jQuery plugins, I often find myself using custom jQuery selectors like :focusable and :closeto to simplify common filters in my code. For example, the :focusable selector is defined as follows: jQuery.extend(jQuery.e ...

Cordova is having trouble locating the JAVA_HOME directory

Despite numerous attempts, I have yet to find a solution to my issue. I am in the process of developing a Cordova Android app, but consistently encounter failures with cordova requirements due to an inability to locate JAVA_HOME. The error message I receiv ...

Dual Socket.io connectivity

Here's a simple question I have. I am running a Node.js server with the following code snippet: io.on('connection', function (socket) { console.log('connection'); }); On my webpage, I have this line of code: var socket = io(); ...

The cookie sent by the server does not replace the current cookie in place

I am currently working on an express application and utilizing the cookie-session module for managing sessions. My application consists of two paths: https://example.com/abc/def and https://example.com/abc/ghi. I have observed that when I visit one path, ...