score:16
Library author here. I'm always fascinated by new ways people can invalidate my assumptions. I mean that in a sincerely positive way, as it results in learning.
🏁 Final Form makes the assumption that your validation functions are "pure" or "idempotent", i.e. will always return the same result when given the same values. This is why it doesn't run the synchronous validation again (just to double check) before allowing the submission: because it's already stored the results of the last time it ran it. By using an outside timer, you've invalidated that assumption.
If you have a better/simpler/"more official" solution, I'd still love to see it!
No need for mutators or decorators for this problem.
The more official way to do this would be to run the check (you could even reuse this.validate
) in onSubmit
. The only tricky part is that the error will come back as meta.submitError
, so you need to check for both when displaying your error. Like so:
score:1
Since you want to enforce re-validation OR stop submission of form based on the interval
, why not use disabled
on submit button?
// interval less than 900 = 15 minutes
<button type="submit" disabled={this.state.interval>=900}>
Submit
</button>
I have also read docs of react-final-form
but I thinks it's more easy unless you have a specific case to address using meta
.
score:1
Got another use case where manual triggering validation is needed: In this case we got an student form, in case we got a new student, a field called temporary password must be fullfilled, if not that field is not mandatory, to keep it simple we update the validation schema on the fly (we had a similar case with a validation that needs to be included whenever some fetch operation was completed).
We applied @uche-ozoemena and it worked fine, but @erik-r is this solution considered a hack or is something that we can use as an approved workaround in scenarios where we need to manually trigger validations?
We got something like (using fonk-final-form):
React.useEffect(() => {
if (isUserCreation) {
const newDataFormvalidationSchema = {
...dataFormvalidationSchema,
field: {
...dataFormvalidationSchema.field,
temporaryInitialPassword: [
...dataFormvalidationSchema.field.temporaryInitialPassword,
Validators.required,
],
},
};
dataFormValidation.updateValidationSchema(newDataFormvalidationSchema);
}
}, [isUserCreation]);
return (
<Form
initialValues={initialData}
mutators={{ mutateValue: mutateValue }}
onSubmit={values => {
save(values);
}}
validate={dataFormValidation.validateForm}
score:2
You're already putting a function inside onSubmit
, why not just add the functionality you want to it? event.preventDefault()
and then work with your validate function, it' s a part of the component and accessible to you.
handleOnSubmit(e){
let value = document.querySelector("input").value
if (!!this.validate(value)){
e.preventDefault();
alert("Prevented submit event")
} else{
alert("Form submitted")
}
}
now just use this function in the form onSubmit
prop(I put in bot since i wasn't sure about the component structure):
<Form onSubmit={this.handleOnSubmit}>...</Form>
<form onSubmit={this.handleOnSubmit}>
And remove the submitListener decorator from the Form component:
decortaor={submitListener}
Now it will check the validation before submitting and prevent it if not validated.
score:2
So I have found a way to do this! 🎉
I use a mutator and use it's changeValue
function to 'change' the value of the relevant field (I supply the same value). This in turn notifies all relevant parties of the change to the form's state, and a validation is triggered. The key is to call the mutator inside the submit handler, which therefore ensures that the validation is performed when the form is submitted. Have a look at this new Sandbox.
The relevant bits are as follows:
// this is a stateful component
...
...
mutateValue([name], state, { changeValue }) {
// change the value to the same value, thus
// triggering a revalidation of the same value
changeValue(state, name, value => value);
}
handleSubmit(values) {
alert("submitted");
}
render() {
return (
...
...
<Form
onSubmit={this.handleSubmit}
mutators={{ mutateValue: this.mutateValue }}
render={({
handleSubmit,
form: {
mutators: { mutateValue }
}
}) => {
const mutateBeforeSubmit = values => {
// supply the name of the relevant form field
mutateValue("revalidate");
// submit handler gets called if revalidation still passes
handleSubmit(values);
};
return (
<form onSubmit={mutateBeforeSubmit}>
...
...
</form>
);
}}
/>
...
...
And because it's triggering the same validation mechanism, meta
gets used accordingly!
If you have a better/simpler/"more official" solution, I'd still love to see it!
Source: stackoverflow.com
Related Query
- How to rerun validation on submit in React Final Form
- How to submit a React form on <select> element change, but keep validation for other inputs in the form?
- How do I add validation to the form in my React component?
- React Formik - Trigger validation only on form submit
- React formik form validation: How to initially have submit button disabled
- How to set/change Field value from external user action 🏁 React Final Form
- How to submit form component in modal dialogue using antd react component library
- How to submit a form in React Native
- Formik React with 2 buttons (Submit and Save) to submit form - Save button not to trigger validation
- How to apply Form validation for React Material-UI TextField and Select?
- How to test function and inner statement after form submit handler in jest/enzyme react
- How to format the value of a checkbox Field using React Final Form Field Array?
- How to give validation in multi step form using react
- How to create a submit button in react-admin which changes appearance and behaviour depending on form data and validation
- multiple form created in single js file. How to validate single form field validation on form submit in ant design?
- I use React js and Material-UI. How can i validate "correct" green color validation on button submit click?
- react final form onBlur prevents validation
- React Final Form reset form fields and validation but retain submitSucceeded
- How to add Link from react router dom to the submit button with the default Submit validation
- Form Validation in material UI React - how to implement form validation for dropdown list
- How can I on Submit my Form redirect the Results to another Page in React
- How to submit react form fields on onChange rather than on submit using React-Hook-Form library
- React how to trigger form submit on input blur?
- how to test button that call submit form using jest and react testing library
- How to access values by key from modified React final form
- How to show validation errors on form using React
- React Final Form How to pass form values in a modal button?
- How to pass input value on form submit in react
- How to trigger popup notification on submit of a form in React using React Router navigate hook?
- React Functional Component: How to prevent form from submitting if validation failed
More Query from same tag
- Best way to handle similar components in ReactJS?
- Having trouble rendering data in react component
- Error installing reactjs: Error unexpected end of JSON input while parsing near
- React: Printing to the console executes after changes, instead of before, as it would be logical
- ReactJS, incrementing/decrementing a rendered value with rendered buttons
- Calling .then on a dispatch in axios/react
- Superagent keeps sending same image repeatedly
- How to display elements in JSX based on OnChange of react-select element
- How to fix : Unexpected keys...found in preloadedState argument passed to createStore.Expected to find one of the known reducer keys instead in Redux?
- how to separate a menu and menu tab content width in 'Ant Design'?
- Component is not found even though package has been imported
- highchart Customclass css not applied to tooltip for dumbbell series
- React/Typescript: How to get json file data
- React simplest webpage doesn't display anything in browser
- Warning: Using UNSAFE_componentWillMount in strict mode is not recommended (upgrade to CRA 4.0.2)
- onClick a button setState to a value in reactjs instead of undefined
- Undefined method in react.js
- Does react-router need specific guidance when using Flow types?
- Page not geting updated on react
- react formik disable submit button with form validity
- <select> Initial value is showing undefined (React js)
- Is there a way in jest to check for a div by classname and then check the style?
- Angular 2 way for creating wrapper component
- How to make next-auth User Session Data Globally accessible from _app.js server-side?
- With Firebase , using react hooks , objects are not valid as a React child , (If you meant) to render a collection of children, use an array instead
- Material UI Autocomplete not working using modified TextField
- How in Material UI to pass a props or a condition to a nested style method
- React - Cannot dispatch onChange event from input text element programatically
- Is there a way to determine the current font-size of a DOM element in ReactJS?
- Style props in component in React