Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected:

export default function Check() {
  const label = { inputProps: { "aria-label": "termsOfService" } };

  const formSchema = yup.object().shape({
    termsOfService: yup
      .boolean()
      .oneOf([true], "Required.")
  });

  const formik = useFormik({
    initialValues: {
      termsOfService: false,
    },
    validationSchema: formSchema,
    onSubmit: (values) => {
      //logic
    },
  });

  return (
    <Checkbox
        {...label}
        name="termsOfService"
        id="termsOfService"
        onChange={formik.handleChange}
        error={
          formik.touched.termsOfService &&
          Boolean(formik.errors.termsOfService)
         }
        value={formik.values.termsOfService}
        helperText={formik.touched.termsOfService && formik.errors.termsOfService}
     />
}

The issue is that the "Required" error message is not displaying when the Checkbox is left unchecked. I've received the following error in my console:

"Warning: Received false for a non-boolean attribute error.

If you want to write it to the DOM, pass a string instead: error="false" or error={value.toString()}.

If you used to conditionally omit it with error={condition && value}, pass error={condition ? value : undefined} instead."

I've tried various adjustments like:

       error={
          formik.touched.termsOfService &&
          Boolean(formik.errors.termsOfService)
       }

But none of them have resolved the issue so far. Just to mention, I am working on Next.js. Interestingly, everything works fine when the Checkbox is checked..

Any insights on what might be causing this problem? Thank you!

Answer №1

Mistake in assigning a boolean value when error is not a boolean type. Instead of using Boolean(...) to assign formik.errors.termsOfService, remove the Boolean function.

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

Is there a way to prevent the conversion of .json/.webmanifest URLs into base64 strings?

I've been grappling with an issue for quite some time now. In my VSCode vite-react-typescript project, I have a link in the index.html file pointing to a webmanifest, which is essentially a json file with a different extension. After building my app, ...

I'm encountering an issue with Regex.test

When working with the following JavaScript code... $.post(url, data, function (json) { var patt = new RegExp('/^\[{"dID":/'); if (patt.test(json)) { //output json results formatted } else { //error so o ...

Leveraging the Spread Operator in Redux mapDispatchToProps with SweetAlert2

When I add the swal action creators to the mapDispatchToProps function like this: function mapDispatchToProps(dispatch) { return { getAnimal: (_id) => dispatch(getAnimal(_id)), ...swal } } The issue aris ...

Some elements in the DOM appear to not be rendering even though they are present in the HTML source code

As a newcomer to web development, I have stumbled upon a perplexing issue. In my usage of d3.js (specifically the script found here), I have been attempting to incorporate additional features. I modified my JavaScript code to include a simple <p> ele ...

Leverage the power of JSON to efficiently represent a collection of string

Currently, I am engrossed in reading the 3rd edition of JavaScript Pocket Reference. The author makes an interesting statement in chapter 5 - Objects on page 75: In JavaScript, objects are dynamic, allowing properties to be added and deleted at will. Int ...

How can I enable a button in a React application when the text input is not populating

For my Instagram MERN project, I have implemented a Comment box feature for users. The Post button starts off disabled and becomes enabled when text is entered. However, despite entering text, the button remains disabled, preventing submission. Below is th ...

In React, the functionality of rendering components conditionally is not functioning properly

I am looking to conditionally display either the Login component or Menubar component based on the value of the isLogin state. If the isLogin state is false, I want to render the login page. If it is true, I want to render the Menubar page. To achieve thi ...

Can the data from these JSON elements be obtained?

Suppose I have a JSON file with the following structure: { "update" : { "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a6aea2aaaf83a4aea2aaafeda0acae">[email protected]</a>":{ "1234": {"notfication" ...

The API designed to accept JSON data via a POST request is receiving a different data type than expected

I have a task to develop an API that receives JSON data in NODE.JS via the POST method. To simplify request management, I utilize Express and BodyParser library to handle the body of POST requests. The data is structured in a JavaScript object like this: ...

jQuery does not support displaying output using console.log

I have a JavaScript code that uses jQuery. However, when I click the #button_execute button, the console.log inside the callback function of .done doesn't display anything on the console. I'm not sure how to troubleshoot this issue. $("#button_e ...

What is the best way to display an alert when the button is clicked repeatedly?

Is it possible to keep displaying the alert every time we click the button, rather than just once after clicking it? I currently have an alert set to trigger when a button is clicked, but it disappears after 3 seconds. How can I make it show up again with ...

Node.js command prompt claims that 'react is non-existent'

Hello everyone! I'm excited to ask my first question on this site. I am relatively new to coding and currently learning React. Yesterday, I started working on my first project. Today, when I tried to initialize live-server and babel compiler for my J ...

Node JS Request Params 500 Error

When generating the URI, everything appears to be in order and the list data is displayed on the page. However, when sending the request in the request method, a 500 error occurs instead of the body being returned. Here is the URI: http://yufluyuinnepal.c ...

Is there a way to hide the row select option for individual rows in MUIDatatables without affecting the multiple row select options?

Is there a way to hide the checkbox in the header row that allows selection of all rows at once? I prefer to manually select multiple options by clicking on each individual row. Can the row select option be hidden? ...

Encountering a build error in Next.js 13 when attempting to fetch an API route within a server component

I encountered an issue while building my next app (yarn run build). To troubleshoot, I created a new clean project and tested it. The problem seems to be with my route (/api/categories/route.ts) export async function GET() { return new Response(JSON.str ...

ReactJS Material-UI Tooltip and Popper overlapping issue

How can I make the MUI tooltip appear beneath the MUI Popper, with the popper overlapping the tooltip? Is there a way to modify the z-index for only a specific portion of the elements without affecting the global styles when using external CSS? Here is a ...

Use the ng-pattern regex to specifically identify instances where a pattern occurs only once

Looking for a string pattern 'abcd' followed by a colon(:) and any number of integers, with the restriction that this pattern cannot be repeated. Here are some examples of valid patterns: - abcd:23415 - abcd:23 And invalid patterns: - asda:4 ...

Tips for utilizing ng-repeat with a function that generates a fresh object?

My HTML code includes the following element: <button ng-click="console.log(key)" ng-repeat="(key, value) in getLocalStorageKeys() track by $index"> In my JavaScript file, I have the following function: $scope.getLocalStorageKeys = function(){ ...

"Utilize JavaScript to detect both the loading and unloading events on a webpage

I attempted to capture the window.open onload and onunload events. The issue arises when I use URLs from other domains. For example: When the URL is for the same page, both events trigger as desired. window.open("/") View PLUNKER with same page URL .. ...

Develop an array using a variable's value in JavaScript

I need assistance with creating an array of variable length based on a dynamic value ranging from 1 to 15. The goal is to populate the array differently depending on the specific value of the variable. For instance, if the variable's value is 1, I wo ...