Yup validation may not accurately validate every field

I am facing an issue with validating a form using yup. The problem arises when I attempt to iterate over the errors thrown by yup, as I discovered that the last field I enter does not get validated:

    const schema = yup.object().shape({
        age: yup.number().required("age is required"),
        name: yup.string().required("name is required"),
        email : yup.string().required("email is required"),
    });
    
    try{
        schema.validateSync({form}, {abortEarly: false})
    }catch(e:any){
        let err = {
            age : '',
            name : '',
            email : '',
        }
        
        e.inner.forEach(error => {
            err[error.path] = error.message
        })
    }
    
    console.log(err)

For instance, when I input the name and age first, I receive an error stating that the email is not valid even though it is filled in:

let form = {
   age : '32', // filled first
   name : 'mike',  // filled second
   email : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e2327252b0e2a2b38602d2123">[email protected]</a>',  // filled last
}

The resulting error object shows:

err = {
   age : '',
   name : '',
   email : 'email is required',
}

A similar issue occurs with the name field if I fill in age and email, where generally the last field will not be properly validated. Are there any solutions to this problem?

Answer №1

When using

schema.validateSync({form}, {abortEarly: false})
, make sure to pass the form data as an object with spread syntax like
schema.validateSync({...form}, {abortEarly: false})
or simply as
schema.validateSync(form, {abortEarly: false})
.

Using schema.validateSync({form}) will validate the object {form: form} and not the actual form data fields such as age, name, and email.
    {
       age : '32', 
       name : 'mike', 
       email : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8de0e4e6e8cde9e8fba3eee2e0">[email protected]</a>',
    }

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

What is the best way to dynamically insert values into a JSON object?

I'm currently working with a JSON object in Angular and I need to dynamically add values that the user enters. Despite searching extensively, I haven't found a straightforward method to achieve this. I simply want to understand how to append key- ...

I encountered an unexpected Uncaught TypeError in Firebase: It seems that the property 'initializeApp' is not defined. I am puzzled as to why 'firebase' is not recognized

Having trouble recognizing Firebase even with the proper import in the configuration file. Any idea why? import firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const firebaseConfig = { apiKey ...

What is the best way to instantly update $scope when working with non-angular code?

Working with a non-angular library requires establishing communication between them. <div id="MoipWidget" data-token="{{personaltoken}}" callback-method-success="successCB" callback-method-error="errorCB"></div> Upon page load, a token must b ...

Manipulate the url bar using ajax and window.location

When making an AJAX request using .load, everything works perfectly. However, there is an issue with the URL bar. I am trying to change the URL displayed in the bar. For instance, when the ajax loads the about/contact page, I want the URL bar to show about ...

What is the most effective way to assign req.body values to an attribute of a class?

I am currently working on a class that serves as a controller to execute a method when called from a route. In the list method, I am trying to assign a value to my dataStore attribute without specifying a particular type since I am unsure of what type it s ...

Exploring the combination of Express router, Auth0, and plain Javascript: A guide to implementing post-login authentication on a router

After creating a front end with vite using vanilla javascript and setting up a backend with node.js express routes, I successfully integrated swagger for testing purposes. I have managed to enable functionalities such as logging in, logging out, and securi ...

Data Mapping Issue: Child Component Unable to Receive Data

I am currently trying to map all the data to a Card Component without using an Arrow function. I can see the data when I console log it manually, but for some reason, it's not showing up when I try to map it to the child component. I specifically wan ...

JavaScript code that triggers when a checkbox is not selected

I'm attempting to dynamically add an input field when a checkbox is clicked, with the intention of having the checkbox already checked by default. However, I am encountering an issue where the checkbox remains unchecked even after the input field is d ...

How come the owl carousel enqueued is functioning seamlessly with the NewsMag Pro theme version but experiencing issues with the default WordPress Installation?

As I work on developing and submitting a new WordPress plugin, my objective is to showcase a snippet of our main site, newyorkbusinessreview.com. This snippet should include our selection of books and carousel sliders featuring our published journal articl ...

Setting up of imagemagick node module using linuxbrew

Having trouble installing imagemagick-native as it's showing an error. Tried using the following command to install: npm install imagemaick-native --save > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c45414d ...

The iframe is displaying a MIME warning for pdfmake: Resource being interpreted as a Document but transferred with MIME type application/pdf

We are developing a single-page application using Vue.js. Our goal is to generate a PDF on the client side, and we have chosen pdfMake from npm for this purpose. As per the documentation, to display the generated PDF within an <iframe>, you can simp ...

Guide to setting up nodejs modules within a specific app directory on your machine

Currently, I am enrolled in a node.js course through frontendmasters.com. In this particular course, it seems to have been recorded at least a year or two ago. The instructor initiates by setting up an application directory called 'express', then ...

Problem with applying Jquery Datatable in conjunction with Bootstrap 4 modal

My current setup involves a datatable that looks like this: Whenever a user clicks on the number of items, it opens a Bootstrap 4 modal like this: However, I am facing an issue with the search and pagination functionality when the datatable is within the ...

What is the best way to iterate through array elements with AngularJS?

I am looking to showcase array values using the ng-repeat directive, and then call the getimage function with itemid and photoidlist in order to retrieve the image URL. The JSON data that I have is as follows: $scope.productslist = { "json": { "re ...

Alter the HTML content prior to the templating process

Utilizing the Mustache template script for rendering my JSON values has been helpful. One thing that I've been pondering is whether it's possible to apply .data() to the object before rendering it into the HTML. To provide a clearer example, co ...

Isolated directive with two-way binding in Angular, but the property is not defined?

Confusion arises when trying to understand the concept of two-way data binding. Let's take a look at the code snippet below: .directive('mupStageButtons', function() { return { transclude: true, template: '<span ...

"Typedoc indicates that no entry points were detected"

This is my main.ts file, but I had renamed it to index.ts later. However, I still encountered the same error multiple times as shown in the terminal output below: https://i.sstatic.net/hFHmX.png Below is the content of my tsconfig.json file: https://i.s ...

Restarting an Angular app is necessary once its HTML has been updated

I've encountered an interesting challenge with an application that combines MVC and Angular2 in a not-so-great way. Basically, on the Index page, there's a partial view loading the Angular app while also including all the necessary JavaScript li ...

Utilize JSON data to display markers on Leaflet maps

I am exploring the world of Leaflet and I have a question about loading markers from a database into a leaflet map using PHP. In my PHP code, I extract latitude and longitude data from the database based on the selected ward and encode it in JSON format. ...

What can be done to prevent the angular material select from overflowing the screen?

I have integrated an Angular Material Select component into my application, which can be found here: https://material.angular.io/components/select/overview. The issue I am facing is that when the select element is positioned near the bottom of the screen a ...