简体   繁体   中英

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.

表格

  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!

For Question 1 - At least one of them should be selected

Try below validationSchema

const validationSchema = Yup.object({checked: Yup.array().min(1, 'Select atleast one option of your interest') });

in FormIk use initialValues like below: <Formik initialValues={{checked: []}} />

For Question 2 - Other field validation you can check yup api documents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM