Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup validation for multiple checkboxes

I need to create the below field with multiple checkboxes. I need the following validations:

  1. At least one of them should be selected
  2. If its the other field user need to add the text to the input field

I need to write a yup validation to achieve this.

the form

like image 580
Anjula Samarasinghe Avatar asked Oct 25 '25 11:10

Anjula Samarasinghe


1 Answers

  1. At least one of them should be selected:
    This is how you'll do that logic using yup validation rules
const validationSchema = yup.object().shape({
  assets: yup.array().min(1).of(yup.string().required()).required(),
});
  1. If its the other field user need to add the text to the input field:
    You can also do this logic using Formik but I suggest you to create a local state for "assets" and if you wanna create new asset using text field just push that new asset in assets local field and then it will automatically render that new asset on the screen.
    And then you can checked or unchecked that new asset. I hope you got the point.

    This is the code snippet you can check!
   import { useState } from "react";
    import * as yup from "yup";
    import { FieldArray, Formik } from "formik";
    
    const initialValues = {
      assets: [],
    };
    
    const validationSchema = yup.object().shape({
      assets: yup.array().min(1).of(yup.string().required()).required(),
    });
    
    function Form() {
      const [newAsset, setNewAsset] = useState("");
      const [assets, setAssets] = useState([
        "Property",
        "Motor Vehicles",
        "Financial Assets",
      ]);
    
      const handleAddNewAsset = () => {
        if (newAsset) {
          setAssets([...assets, newAsset]);
          setNewAsset("");
        }
      };
    
      return (
        <>
          <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={(values) => {
              console.log("form values if validation succeed: ", values);
            }}
          >
            {(props) => (
              <form onSubmit={props.handleSubmit}>
                <FieldArray
                  name="assets"
                  render={(arrayHelpers) => (
                    <>
                      {assets.map((asset, idx) => (
                        <label className="form-check-label my-1">
                          <input
                            name={`assets.${idx}`}
                            type="checkbox"
                            className="form-check-input"
                            value={asset}
                            checked={props.values.assets.includes(asset)}
                            onChange={(e) => {
                              if (e.target.checked) {
                                arrayHelpers.push(asset);
                              } else {
                                const index = props.values.assets.indexOf(asset);
                                arrayHelpers.remove(index);
                              }
                            }}
                          />
                          <span className="mx-2">{asset}</span>
                        </label>
                      ))}
                    </>
                  )}
                />
                <input
                  type="text"
                  value={newAsset}
                  onChange={(e) => setNewAsset(e.target.value)}
                />
                <button type="button" onClick={handleAddNewAsset}>
                  Others (specify)
                </button>
              </form>
            )}
          </Formik>
        </>
      );
    }

I hope it will help. Thanks!

like image 70
Jazim Abbas Avatar answered Oct 27 '25 01:10

Jazim Abbas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!