What could be causing the failure of my yup validation schema for a string array?

Can anyone provide insight into why this validation issue is occurring? I am implementing a schema using yup to ensure that the data within an array are strings. Below is the yup schema I am working with:

signUpSchema: async (req, res, next) => {
    const signUpSchema = yup.object().shape({
      username: yup
        .string()
        .required('name is required')
        .typeError('name must be a string'),
      email: yup
        .string()
        .email('email must be a valid email')
        .required('email is required')
        .typeError('email must be a string'),
      ...
      locationTracking: yup
        .array()
        .of(yup.string())
        .required('locationTracking is required')
        .typeError('locationTracking must be an array')
        .min(1, 'locationTracking must have at least one location'),

    });

    try {
      await signUpSchema.validate(req.body);
      next();
    } catch (error) {
      next(error);
    }
  },

I have also tried incorporating the required and typeError methods in my code:

locationTracking: yup
            .array()
            .of(yup.string().require().typeError('data must be strings'))
            .required('locationTracking is required')
            .typeError('locationTracking must be an array')
            .min(1, 'locationTracking must have at least one location'),

        });

While the schema states that locationTracking should be an array, it does not specifically enforce that the elements must be strings. This results in numbers, booleans, and other data types passing the validation process. I am unsure of what mistake I may be making and have been unable to find a solution online.

The data being validated is from req.body sent as JSON via postman. I initially suspected some form of type coercion, but upon inspection, the data types returned are numbers, booleans, etc., managing to bypass my validation checks.

Answer №1

const validationSchema = yup.array().of(yup.number().min(2));

await validationSchema.isValid([2, 3]); // => true
await validationSchema.isValid([1, -24]); // => false

validationSchema.cast(['2', '3']); // => [2, 3]

Check this out for more information.

Your custom code snippet

locationTracking: yup
            .array()
            .of(yup.string().min(1, 'Ensure at least one location is included in locationTracking').required())
            .required('Include at least one location in locationTracking')
        });

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

The request is unsuccessful due to the absence of the 'Access-Control-Allow-Origin' header

I've set up a form using Get Response (the email client) and I'm attempting to implement ajax in order to display a custom success or failure message upon submission. The code seems to be functioning correctly. However, as soon as I connect the a ...

Tips for transferring the value of ng-model to multiple controllers

Is it possible to access the value of an ng-model from two different controllers? While I am aware that using a service is one way to share data between controllers, I am struggling to figure out how to pass the value of an ng-model to a service for this ...

Limiting Firebase communication to Electron Application

Is there a way to restrict access to a Firebase realtime database or any other database from an Electron application? I understand that you can restrict access by specifying the server your website is hosted on, but since Electron is local, are there any o ...

What is the process for identifying the ActiveX control being referenced on a webpage?

After developing a web application using ASP.NET Web Forms, I encountered a challenge with a client who has strict security policies. Whenever they try to access the web page, Internet Explorer displays a message stating: Your security settings do not all ...

The <Button> element is incompatible with popups. (HTML, CSS, JS)

I've been struggling with this issue. I used CSS color values to create a smiley face, but when I added a button it messed up the design (adding an unwanted circle around the center of the smiley). I attempted to synchronize the button tag with the po ...

Can you explain the functionality of express-async-handler?

Hello, I'm trying to understand the purpose of express-async-handler. I came across it in a repository I was exploring. According to the documentation, express-async-handler is a simple middleware designed to handle exceptions within asynchronous exp ...

I am looking to modify the file name in the save as dialog box whenever the user performs a right-click

In my current project, I am utilizing PHP along with javascript/jQuery. I have a specific requirement where I need to alter the filename displayed in the save as dialog when a user right-clicks on an image and chooses to save it. For instance, I wish to ...

Tips for transferring information to the recipient and storing it as a cookie

Although I have a good grasp of coding fundamentals, I'm currently delving into the world of APIs. My current project involves creating an API that authorizes users to access their information within a game. The primary goal is to send data from my N ...

Using more than one class at a time is causing issues

Essentially, I have a div and I want to create an exercise where I apply three different classes using vue.js. I attempted to use v-bind:class, specifically :class, but can I bind a class directly from CSS? This is what I tried: html <div :style="[my ...

What error am I making when attempting to validate an email address with RegExp?

I have been attempting to verify the format of an email address using the script below, but I seem to be making a mistake somewhere. When I try to match the reg_1 pattern with str_1, str_2, str_3, I consistently get a false result. Can anyone help me und ...

Authenticate through navigation on an alternate component

I am in the process of developing a user interface that includes a side navigation and header bar. However, if the user is not logged in, I wish to redirect them to the login page. The primary component structure is as follows: class App extends Componen ...

Is there a way to troubleshoot and fix the ESM error while using Phusion Passenger?

As I attempt to deploy my NodeJS API on a production server using Phusion Passenger, I encounter an issue with importing/exporting modules in the latest ECM syntax. When trying to access my API, Passenger presents the following error message: Error [ERR_RE ...

issue with transparent html5

Here is the code snippet I am struggling with: function clear(){ context2D.clearRect(0, 0, canvas.width, canvas.height); } function drawCharacterRight(){ clear(); context2D.setTransform(1, 0.30, 1, -0.30, 10, 380);//having issues here c ...

Links have a longer transition delay compared to the content

In a unique JavaScript function I've developed, the my-content-section-visible class is removed and replaced with my-content-section-hidden. This change is being made to hide a particular div using a smooth transition effect. The transition itself is ...

Receiving a 200 ok status, but encountering a response error in Postman

Receiving a response with a 200 OK status, but encountering an error message in Postman. { "errors": "Unable to log you in, please try again.", "success": false } Post Url: [{"key":"Content-Type","value":"application/json","descript ...

Create distinct 4-digit codes using a random and innovative method, without resorting to brute force techniques

I am working on developing an application that requires generating random and unique 4-digit codes. The range of possible codes is from 0000 to 9999, but each day the list is cleared, and I only need a few hundred new codes per day. This means it's fe ...

Troubleshooting issue with rendering <li></> using array.map: Map's return statement is producing undefined output

Trying to implement pagination in a React project and facing issues with rendering a set of li elements within an ul. The renderPageNumbers function is returning undefined in the console, even though I can see the array being passed and logging out each el ...

console rendering duplication in React

Why am I seeing duplicate log entries in the console? While working on another project, I noticed that the number of HTML elements being added using jQuery was twice as much as expected (specifically while building a notification framework). To investigate ...

Issue with Mongoose: Create operations are not functioning properly right after performing Delete operations

I need to refresh my collection by deleting all existing documents and then repopulating them with new data from an API call. But when I try running the delete operations first, no new documents are created. Below is a simplified version of my controller ...

Proceed the flow of event propagation using the react-aria button element

In the react-aria library, event bubbling for buttons is disabled. I am facing an issue where my button, which is nested inside a div that acts as a file uploader, does not trigger the file explorer when clicked due to event bubbling being disabled. How ...