Formik validate initial values on page load - reactjs

Code below validate when submit and onFocusOut of textbox fine, What I expect it to trigger validation first reload of the page with initial values.
Tried validateOnMount, as well as others but not worked.
Whats missing here?
const RoleValidationSchema = Yup.object().shape({
Adi: Yup.string()
.min(2, "En az 2 karakter olmalıdır")
.max(30, "En fazla 30 karakter olmalıdır")
.required("Gerekli!")
})
const Role = (props) => {
return (
<div>
<Formik
onSubmit={(values, { validate }) => {
debugger
validate(values);
alert("Submietted!")
props.handleFormSubmit()
}}
initialValues={{
Adi: "d"
}}
validationSchema={RoleValidationSchema}
validateOnMount={true}
validateOnChange={true}
validateOnBlur={true}
render={({ errors, touched, setFieldValue, ...rest }) => {
debugger
return (
<Form>
<Row>
<Col sm="12">
<Label for="Adi">Rol Adi</Label>
<FormGroup className="position-relative">
<Field
autoComplete="off"
id="Adi"
className="form-control"
name="Adi"
type="text"
/>
<ErrorMessage name="Adi">
{(msg) => (
<div className="field-error text-danger">{msg}</div>
)}
</ErrorMessage>
</FormGroup>
</Col>
<Tree dataSource={treeData} targetKeys={targetKeys} expandKeys={[]} onChange={onChange} />
</Row>
<button type="submit" className="btn btn-success" > Kaydet</button>
</Form>
)
}}
/>
</div>
)
}

This worked for me to show validation error on form load.
useEffect(() => {
if (formRef.current) {
formRef.current.validateForm()
}
}, [])

Try to add enableReinitialize Prop to your Formik Component
<Formik
enableReinitialize
......
/>

I had a bit specific case with dynamic Yup schema. Schema was generated based on API data. And validateOnMount was failing as when component was mounted there was no schema yet (API response not received yet).
I end up with something like this.
Inside component I used useEffect. Notice: I used useRef to be able to reference Formik outside of form.
useEffect(() => {
if (formRef.current) {
// check that schema was generated based on API response
if(Object.keys(dynamicValidationSchema).length != 0){
formRef.current.validateForm()
}
}
}, [initialData, dynamicValidationSchema])
Formik:
<Formik
innerRef={formRef}
enableReinitialize
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={props.handleSubmit}
>

It's possible to provide a initial value for validation in the "initialIsValid" prop.
const validationSchema= Yup.object()
const initialValues = { ... }
const initialIsValid = schema.isValidSync(initialValues)
return <Formik
initialValues={initialValues}
validationSchema={validationSchema}
initialIsValid={initialIsValid }
...
>
...
</Formik>

The only solution I found is to explicitly add initialErrors={{..}} to Formik.
In the below example, it's added depending on some condition. Unfortunately that duplicates the Yup validation/message which I also have in the schema. Nothing else worked, no validateOnMount or anything else.
<Formik
enableReinitialize
validationSchema={schema}
onSubmit={ (values) => {
submitForm(values);
}}
initialValues={initialFormValues}
/* Unfortunately a duplication of Yup Schema validation on this field,
but can't force Formik/Yup to validate initially */
initialErrors={!isEmptyObject(initialFormValues) &&
initialFormValues.inactiveApproverCondition &&
{'approverId': 'Selected Approver is no longer eligible. Please choose a different Approver to continue.'}}
>

You should try updating your code follow this
render={({ errors, touched, setFieldValue, isValid, ...rest })
and
<button type="submit" className="btn btn-success" disabled={!isValid}> Kaydet</button>

Related

Handling routes after submitting form

Hello my great teachers of StackOverflow. I'm going through ben awads fullstack tutorial and am trying to add an image upload feature to create post. Looks like everything works well, inserts posts (including image) into db. However, after submitting my form, it wont send me to the home page (stays on the same page with current values inserted). It is set so that if there are no errors, route me to the homepage. Im assumming i have no errors cause the post inserts into database. Any help will be greatly appreciated.
const CreatePost: React.FC<{}> = ({}) => {
const router = useRouter();
const [createPost] = useCreatePostMutation();
return (
<Layout>
<Formik
initialValues={{ title: "", text: "", file: null }}
onSubmit={async (values) => {
console.log(values);
const { errors } = await createPost({
variables: values,
});
if (!errors) {
router.push("/");
}
}}
>
{({ isSubmitting, setFieldValue }) => (
<Form>
<InputField name="title" placeholder="title" label="Title" />
<Box mt={4}>
<InputField name="text" placeholder="text..." label="Body" />
</Box>
<Input
mt={4}
required
type="file"
name="file"
id="file"
onChange={(event) => {
setFieldValue("file", event.currentTarget.files[0]);
}}
/>
<Button mt={5} type="submit" isLoading={isSubmitting}>
create post
</Button>
</Form>
)}
</Formik>
</Layout>
);
};
You can use router.push hook.
You need to pass validate function as props to Fomik to prevent submitting only with 2 fields. I have added a basic validate object. But you can use Yup package also. Formik will return an error object inside the form and you need to make sure form does not get submitted in error state. For that get the errors object and as you are using custom Button component pass true/false by checking if any errors exist. I added the code.
You can get more details here.
router.push("/home");
.....
const validate={values => {
const errors = {};
if (!values.title) {
errors.email = 'Required';
}
if (!values.text) {
errors.text= 'Required';
}
if (!values.file) {
errors.file= 'Required';
}
return errors;
}}
<Formik
initialValues={{ title: "", text: "", file: null }}
validate
onSubmit={async (values) => {
.......
{({ isSubmitting, setFieldValue, errors }) => (
..........
<Button mt={5} type="submit" isLoading={isSubmitting} isFormValid={!Object.values(errors).find(e => e)}>
create post
</Button>

React Bootstrap Form.Check with Formik

How can I properly bind Form.Check to a boolean variable using yup and Formik?
React-Bootstrap 4.5 provides an example of using Formik + yup with form inputs. I was able to setup text inputs and selects, but encountered a problem with Form.Check element. I expect it to provide simple boolean value on change, but instead I'm getting an empty array [] or ["on"] when checkbox is checked.
The documentation also has this issue, in the example from the link above form displays this error message:
terms must be a boolean type, but the final value was: ["on"].
My code:
const schema = yup.object({
deactivated: yup.boolean(),
});
const initialValues = {
deactivated: false,
};
return (
<Formik
validationSchema={schema}
onSubmit={(
values
) => {
save(
values.deactivated,
);
}}
initialValues={initialValues}>
{({
handleSubmit,
handleChange,
values,
errors,
}) => (
<Form noValidate onSubmit={handleSubmit}>
<Form.Group controlId="deactivated">
<Form.Check
label="Deactivated"
type="checkbox"
value={values.deactivated}
onChange={handleChange}
isInvalid={!!errors.deactivated}
/>
</Form.Group>
<Button type="submit">Save</Button>
</Form>
)}
</Formik>
);
I was able to handle checkbox changes manually using setFieldValue method:
extract setFieldValue method from Formik
bind checkbox to checked property instead of value
use custom onChange handler: {e => setFieldValue('deactivated', e.target.checked)}
Code:
return (
<Formik
validationSchema={schema}
onSubmit={(
values
) => {
save(
values.deactivated,
);
}}
initialValues={initialValues}>
{({
handleSubmit,
handleChange,
values,
errors,
setFieldValue,
}) => (
<Form noValidate onSubmit={handleSubmit}>
<Form.Group controlId="deactivated">
<Form.Check
label="Deactivated"
type="checkbox"
checked={values.deactivated}
onChange={e => setFieldValue('deactivated', e.target.checked)}
isInvalid={!!errors.deactivated}
/>
</Form.Group>
<<Button type="submit">Save</Button>
</Form>
)}
</Formik>
);

How to reset a certains fields after submit in Formik

I am using Formik and I need to make this logic.
I am have a big form, and after submission I need to reset certain fields in this form
There is 2 buttton: Save and Save & New
save will save the data and redirect.
Save & New will save the data and reset the first two fields.
I tried to use:
resetForm but it resets all the form
setValues does not work
setFieldValues prevents the api request
set values manually also does not work
Here is the code
const initialValues = { value1: "", value2: "", value3: "", value4: "" };
<Formik
initialValues={initialValues}
enableReinitialize
validationSchema={Schema}
validateOnChange={false}
validateOnBlur={false}
onSubmit={(values, { setSubmitting, resetForm }) => {
props.addData(values); // api request
setSubmitting(false);
// resetForm(initialValues); // this will reset all the form fields
// values.value1 = ""; // does not work
}}
>
{({ values, handleChange, handleSubmit, setFieldValue, errors }) => (
<Form>
<Row>
<Field type="text" name="value1" />
<Field type="text" name="value2" />
<Field type="text" name="value3" />
<Field type="text" name="value4" />
</Row>
<StyledRow>
<Button
variant="outline-primary"
onClick={() => {
handleSubmit();
history.push("/tableOverview");
}}
>
Save
</Button>
<Button
variant="outline-primary"
onClick={() => {
handleSubmit();
// this prevents the api request, because of async code I guess
// setFieldValue("value1", "");
// setFieldValue("value2", "");
}
>
Save & New
</Button>
</StyledRow>
</Form>
)}
</Formik>
On submitting the form, you can set whatever the values you dont want to peresist using setFieldValue and later setSubmitting to false, So that the values you want will be persisted and you can submit the form again
Please find the example codesandbox here

handleSubmit function not successfully firing using Formik

I am using Formik + Yup to construct a form but can't seem to get passed a basic issue, I feel like I'm missing something obvious. My handleSubmit function wont fire on button click - even something simple like a console log. If I add a pure function to the onClick button handler it fires, but Formik doesn't seem to be passing down my handleSubmit constructed with the withFormik HOC.
I've tried adding the handler to the Form component, doesn't work there either.
const formikEnhancer = withFormik({
mapPropsToValues: props => ({
firstName: props.firstName || '',
...
}),
validationSchema: yup.object().shape({
firstName: yup.string().required('Please enter your first name'),
...
}),
handleSubmit: (values, formikBag) => {
console.log('test');
}
},
});
const BusinessFundingForm = ({
values,
isSubmitting,
errors,
handleBlur,
handleChange,
handleSubmit,
touched,
data,
}) => {
return (
<Form className="form" id="form-id">
<Row>
<Col xs={12} sm={6}>
<InputField
id="first-name"
type="text"
name="firstName"
value={values.firstName}
onChange={handleChange}
onBlur={handleBlur}
placeholder="First Name"
label="First Name"
/>
{errors.firstName &&
touched.firstName && <Error>{errors.firstName}</Error>}
</Col>
...
</Row>
<Row>
<ButtonWrapper>
<Button
type="submit"
tall
onClick={handleSubmit}
varianttype={
isSubmitting ||
(!!errors.firstName ||
formHelpers.isEmpty(values.firstName))
? 'disabled'
: 'outline'
}
disabled={
isSubmitting ||
(!!errors.firstName ||
formHelpers.isEmpty(values.firstName))
}
text="Submit →"
/>
</ButtonWrapper>
</Row>
</Form>
</FormGrid>
</Element>
);
};
export default formikEnhancer(BusinessFundingForm);
For brevity's sake I deleted all the properties except the firstName property
Sometimes there are errors on the page which prevent Formik from triggering handleSubmit thus its good to check if there are no errors by outputting errors on the screen or console.
To overcome these type of scenarios during development you can always use:
<pre>{JSON.stringify(errors, null, 2)}</pre> as a DOM node so that you are constantly aware of the issue on the UI and then remove it or comment it during committing to your branch.
Also I trust there are no syntax errors on your code because your handleSubmit seems to have extra closing brace.

understanding Formik and React

This is probably not the best place to post this question but where, then?
The code below is taken from Formik's overview page and I'm very confused about the onSubmit handlers:
The form element has an onSubmit property that refers to handleSubmit which is passed on that anonymous function : <form onSubmit={handleSubmit}>. Where does that come from?
The Formik component has an onSubmit property as well:
onSubmit={(values, { setSubmitting }) => { ... }
How do these relate to each other? What is going on?
import React from 'react';
import { Formik } from 'formik';
const Basic = () => (
<div>
<h1>Anywhere in your app!</h1>
<Formik
initialValues={{ email: '', password: '' }}
validate={values => {
let errors = {};
if (!values.email) {
errors.email = 'Required';
} else if (
!/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
) {
errors.email = 'Invalid email address';
}
return errors;
}}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
/* and other goodies */
}) => (
<form onSubmit={handleSubmit}>
<input
type="email"
name="email"
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
/>
{errors.email && touched.email && errors.email}
<input
type="password"
name="password"
onChange={handleChange}
onBlur={handleBlur}
value={values.password}
/>
{errors.password && touched.password && errors.password}
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</form>
)}
</Formik>
</div>
);
export default Basic;
The component takes onSubmit as a prop where you can execute code you want to perform when you submit your form. This prop is also given some arguments such as values (values of the form) for you to use in your onSubmit function.
The handleSubmit form is auto generated from the Formik library that automates some common form logics explained here. The handleSubmit will automatically execute onSubmit function mentioned above as part of its phases (pre-submit, validation, submission). Hope that answers your question!

Resources