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

Using Ajax and PHP to upload an image

I'm looking to implement an image upload feature triggered by a button click with the id of #myid.save. Below is the code I have so far: HTML Code: <canvas id="cnv" width="500" height="100"></canvas> <input id="myid_save" type="submit ...

Why isn't the default value displayed in MUI AutoComplete?

import * as React from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomplete"; export default function MovieComboBox() { const [movieList, setMovieList] = React.useSt ...

Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this? Here is a snippet of my ...

Best practices for working with HTML elements using JavaScript

What is the best approach for manipulating HTML controls? One way is to create HTML elements dynamically: var select = document.getElementById("MyList"); var options = ["1", "2", "3", "4", "5"]; for (var i = 0; i < options.length; i++) { var opt = ...

Hover over with your mouse to open and close the dropdown menu in React JS

Just starting out with React JS and encountering a small issue. I'm trying to make the menu disappear when the mouse leaves that area, so I used onMouseOut and onMouseLeave to close it. However, I noticed that having these options in place prevents th ...

Learn how to effectively display checkboxes in an HTML form with Vue configuration

new Vue({ el: '...', data: { checkeditems: [] } }) <div v-for="item in instituteModel" v-if="instituteModel.length > 0"> <input type="checkbox" id="item.id" value="item.inst_name" v-model="checkeditems"/> </div&g ...

What are the best ways to incorporate mistakes into my JavaScript mortgage calculator?

I am struggling to set up my calculator so that it triggers an error message if the APR goes over 25% or falls below 0. Also, the Loan Term should be greater than 0 and less than or equal to 40, otherwise display an error message. I have attempted differen ...

The AJAX session is triggered twice, without displaying an alert the second time

Upon loading the page, an AJAX session is triggered and then again after clicking. Strangely, the readystate change is not happening the second time around. To troubleshoot, I added an alert box in the function which appears during page load but not on cli ...

Exploring the use of Rails and jQuery to automatically update data through the use of setTimeout and ajax calls

There's a specific page accessible in the browser at "/calendar" that directs to "calendar#index". Utilizing a javascript setTimeout function, I'm attempting to re-fetch and update data on my page using $.get ajax method. $.get("<%= calendar ...

Tips for disabling autofocus on textarea when it is initially created in Internet Explorer browser

By clicking a button, I can generate a new <textarea></textarea>. However, in Internet Explorer, the cursor automatically moves to the newly created text area. Is there a way to prevent this from happening? ...

Altering the text and functionality of buttons with jQuery

A JavaScript method I have is designed to change based on the state of a button, which is determined by using indexOf("..some text.."). $('#add1').click(function(){ if($(this).text().indexOf("Add Me!")) { $.ajax({ type: & ...

The importance of incorporating React into the scope of functional component development

While discussing class components, it's clear that they are part of the global React object. But why is it necessary to import them with every functional component? And do bundlers play a role in this requirement? I've been coding for 5 months n ...

Creating a blank grid using ng-repeat in angularJS

I'm attempting to create an empty grid using angularJS, but I've only been working with it for 2 days so I'm not very experienced. This is what I have come up with so far: <!doctype html> <html ng-app> <head> < ...

Guide to generating customized CSS styles on-the-fly in Vue (similar to Angular's dynamic styling capabilities)

When working with Angular, we have the capability to dynamically set CSS properties. For example: <style ng-if="color"> .theme-color { color: {{color}}; } .theme-background-color { background-color: {{color}}; } .theme-border-color { border-color: { ...

Injecting HTML into Vue component

Currently, I am passing some parameters into a Vue component <Slider :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']" :html="['<div>hello</div>', ' ...

Changing the structure of a JSON array in JavaScript

I'm currently developing an ExpressJS application and I need to send a post request to a URL. My data is being retrieved from a MS SQL database table using Sequelize, and the format looks like this: [ { "x":"data1", "y":& ...

What is the best way to include my PHP session variable within my JavaScript code?

i have a dynamic table that the enables to perform CRUD operations on a database. after logging in the user is directed to index.php, here a table is displayed with values stored in the database table "ajaxtable". i have joined "ajaxtable" table and "membe ...

What is the best way to transform a date such as '2021-06-01T11:17:00-07:00' into the corresponding date and time for a specific location (New Delhi) using JavaScript?

How can I convert a date in the format '2021-06-01T11:17:00-07:00' to ISO standard? What does this format represent? let date = new Date('2021-06-01T11:17:00-07:00'); console.log(date.getHours() + " :" + date.getMinutes()); I ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

Refrain from showing content beneath a certain element

Is there a way to hide all content that appears after a specific element, such as a particular class of div? The issue I am facing involves using a 1&1 webpage builder with a restrictive layout-template enforced by my boss. I am trying to remove the foote ...