Manually set redux-form field and/or form errors
Yes, it does.
You can use validate
and asyncValidate
props to set validator functions for the values of your form (synchronous and asynchronous respectively).
validate
should be a function that either returns an empty object if validations pass or an object detailing validation errors in the form { someField: 'some error', otherField: 'other error' }
asyncValidate
on the other hand should return a Promise
that is resolved normally if validations pass or that is rejected with an object detailing validation errors (see above) if validations do not pass.
handleSubmit
is implemented in such a way that it runs both synchronous and asynchronous validations before calling onSubmit
, so if you've set up validate
and asyncValidate
, those errors should appear in your form/fields automatically without any additional work.
Hope this helps!
Update:
You could also just wait until asyncActionDispatcher
finishes and continue submitting or reject with a SubmissionError
depending on what the results from it were.
function asyncActionDispatcher(values) {
return (dispatch, getState) => {
if (success) {
return Promise.resolve('success')
} else {
return Promise.reject('error')
}
}
}
function onSubmit(values, dispatch) {
// dispatch whatever action you need to dispatch
return dispatch(asyncActionDispatcher(values))
.then(() => {
// i guess you need to do your actual submitting here
})
.catch(error => {
return new SubmissionError({ _error: 'whatever you want here' })
})
}
// and in the component
<form onSubmit={ handleSubmit(onSubmit) }> ... </form>
Sources: Redux-Form docs, wrapped component props documentation, synchronous validation example, asynchronous validation example
Does redux-form have another API to set errors on fields/form?
Another option here when asyncValidate
and other options proposed won't work (for example because validations consider multiple forms) is to dispatch updateSyncErrors
directly. Example usage below:
const { updateSyncErrors } = require('redux-form/lib/actions').default;
dispatch(updateSyncErrors('formName', {
fieldName: 'Some Error Message'
}));
Your handleSubmit()
is called like so:
handleSubmit(values, dispatch, props)
...where one of the properties of that props
Object is a stopSubmit()
function.
That's what you want to use, where it's API is similar to as described here:
stopSubmit(form:String, errors:Object)
// Flips the submitting flag false and populates submitError for each field.
You would need to specify the unique form
string identifier when importing that function yourself and using it, but if you use the version past to your handleSubmit()
(via the props
Object), then you don't need to provide the argument for the first parameter.