jquense / react-formal

Sophisticated HTML form management for React
http://jquense.github.io/react-formal
MIT License
526 stars 52 forks source link

How do I declare Yup data schema for type='checkbox' ? #143

Closed lvdang closed 1 year ago

lvdang commented 6 years ago

// Is this right?

this.customerSchema = yup .object({ permissions: yup.array().required('Permission not checked').max(2), }), });

// <Form.Field name="permissions" type="checkbox" />

    <Form.Field
      name="permissions"
      type="checkbox"
    />
jquense commented 6 years ago

usually for a checkbox you want yup.bool()

lvdang commented 6 years ago

How would I implement multiple checkbox for Form.Field name value?

e.g. yup schemas

this.customerSchema = yup .object({ permissions: yup.object({ green: yup.bool() yellow: yup.bool(), red: yup.bool(), }), });

// How do I declare for multiple box name declaration?

or

jquense commented 6 years ago

For that I use the select list component in React widgets (react-formal-inputs) and an array for the schema

lvdang commented 5 years ago

thanks On Tuesday, April 9, 2019, 2:07:26 AM PDT, Toni Laukka notifications@github.com wrote:

I was looking for same example but couldn't find anser anywhere. Here is a working example. import React from "react"; import ReactDOM from "react-dom"; import Form from "react-formal"; import * as yup from "yup"; import { SelectList } from "react-widgets";

import "./styles.css";

const schema = yup.object({ checkboxes: yup .array() .of( yup.object().shape({ id: yup.string(), name: yup.string() }) ) .default([]) .oneOf([true], "Must choose one") });

class App extends React.Component { handleChange = form => { console.log(form); };

handleError = error => { console.log(error); };

handleSubmit = form => { console.log(form); };

render() { return (

Hello CodeSandbox

Start editing to see some magic happen!

Submit
);

} }

const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);```

Same on codesandbox: https://codesandbox.io/s/7z1q0rnq76

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

user4302 commented 1 year ago

this worked for me, i was validating each of these only if the other one did not have an input

step5ValidationSchema: {
//multiple checkboxes, multi select
    statement: Yup.array().when("plan", {
      is: (plan) => {
        return plan === undefined;
      },
      then: (schema) => schema.min(1, "This field is required"),
      otherwise: (schema) => schema.notRequired().optional().nullable(),
    }),
//multiple radio buttons, single select
    plan: Yup.string().when("statement", {
      is: (statement) => {
        return statement.length === 0;
      },
      then: (schema) => schema.required("This field is required"),
      otherwise: (schema) => schema.notRequired().optional().nullable(),
    }),
  },