I have a React-Final-Form that validates its form fields.
I would like to not invoke validation when a cancel or reset button is clicked. However, if clicking the cancel button click causes an invalid field to render its error message, the onCancel function is never called. This happens even if I set the button type to "reset".
If validate doesn't return a change, only then can the onCancel function be reached.
handleSubmit(values) { console.log(JSON.stringify(values, 0, 2)) }
onCancel() { console.log("cancelled!"); }
render() {
const onSubmit = async values => { this.handleSubmit(values); };
return (
<Form name="form"
onSubmit={onSubmit}
validate={values => {
const errors = {};
if (!values.username) { errors.username = 'Required' }
return errors }}
render={({handleSubmit}) => (
<form onSubmit={handleSubmit}>
<Field name="username">
{({ input, meta }) => (
<input {...input} type="text" placeholder="Username" autoFocus>
{meta.error && meta.touched && <span>{meta.error}/span>}
)}
</Field>
<button type="submit">Submit</button>
<button type="button" onClick={onCancel}>Cancel</button>
</form>
)}/>
);
button
without atype
attribute automatically has asubmit
type, and will thereforetouch
all fields and show any errors, regardless of what itsonClick
function says. To prevent that, addtype=button
. – Chris Chiasson