I'm using Yup to check whether a field (that is set using the state 'groupSelected') has been selected by the user. (The field is a required field)
<Formik initialValues={{title:'', group:{groupSelected}}}
enableReinitialize='true' // since we are setting the formik initial value to state, this is required to update the initial value when state changes
onSubmit={values => console.log(values)}
validationSchema={validationSchema}
I'm able to retrieve the selected values just fine when the form is submitted. However, I'm unsure how to validate if the state has actually been set or not.
group: Yup.string().required()
I tried using the above but I guess it does not work because groupSelected is not a string.
Here is the basic example of Formik with yup.
You can also try this way.
Example:
import React from "react";
import { Formik, Form, Field } from "formik";
import * as Yup from "yup";
const SignupSchema = Yup.object().shape({
firstName: Yup.string()
.trim("spaces no t allowed")
.strict()
.required("Required"),
});
export const MyForm = () => (
<div>
<h1>Signup</h1>
<Formik
initialValues={{
firstName: "",
}}
validationSchema={SignupSchema}
onSubmit={(values) => {
// same shape as initial values
console.log(values);
}}
>
{({ errors, values, touched, setFieldValue, registerField }) => (
<Form>
<Field
name="firstName"
/>
{errors.firstName && touched.firstName ? (
<div>{errors.firstName}</div>
) : null}
<br />
{JSON.stringify(errors)}
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);