-
-
Save jaredpalmer/a8faaab12bc37e6a160a3c9549664f0b to your computer and use it in GitHub Desktop.
import React from 'react'; | |
import debounce from 'utils/debounce'; | |
class EmailInput extends React.Component { | |
checkEmail = value => { | |
// only check if the field passes Yup email validation first | |
if ( | |
!this.props.form.errors[this.props.name].includes( | |
'invalid' /* or whatever your error message is*/ | |
) | |
) { | |
MyApi.checkEmail(value).then( | |
success => { | |
this.props.form.setFieldError(this.props.name, undefined); | |
// if you need to show more info, like a checkbox: | |
// this.props.form.setStatus({ email: true }) | |
}, | |
error => | |
this.props.form.setFieldError( | |
this.props.name, | |
transformErrorToEnglish(error) | |
) | |
); | |
} | |
}; | |
debouncedCheckEmail = debounce(this.checkEmail, 300); // 300ms debounce | |
handleChange = e => { | |
this.props.field.handleChange(e); // this will let Formik's default validation take place | |
this.debouncedCheckEmail(e.target.value); | |
}; | |
handleBlur = e => { | |
this.props.field.handleBlur(e); // this will let Formik's default validation take place | |
this.checkEmail(e.target.value); | |
}; | |
render() { | |
const { field, form, ...props /* like placeholder */ } = this.props; | |
return ( | |
<div> | |
<input | |
{...field} | |
{...props} | |
onChange={this.handleChange} | |
onBlur={this.handleBlur} | |
/> | |
{/** show errors */} | |
</div> | |
); | |
} | |
} | |
export default EmailInput | |
// Usage | |
<Field name="email" component={EmailInput} placeholder="[email protected]" /> | |
// or | |
<Field name="email" render={props => <EmailInput {...props} {...otherPropsYouMightNeed} />} /> |
FWIW I'm not sure this works on v1.1.1.
I get client side validation right after server-side validation and the errors are wiped out.
Similar to: jaredpalmer/formik#834
@cesarcf the field object has the onChange
and onBlur
methods, the form object has errors
, touched
, isValid
, dirty
etc. etc.
Can confirm this also does not work for me. Any error I set with setFieldError
is cleared out on validation of another field.
@davetorbeck I had a similar issue with it being cleared out by my yup
validation. Might not be the best solution but if you whack a setTimeout
around it, it should run on the next loop and after the other validation has run, eg:
setTimeout(() => {
form.setFieldError(this.props.name, EMAIL_EXISTS_ERROR_MESSAGE);
}, 0)
Hello!,
I think this lines is not correct:
this.props.field.handleChange (e);
this.props.field.handleBlur (e);It should be like that, right?
this.props.form.handleChange (e);
this.props.form.handleBlur (e);
This example is so broken :( Did anyone ever get this to work and could you provide an example, please?
Hello!,
I think this lines is not correct:
this.props.field.handleChange (e);
this.props.field.handleBlur (e);
It should be like that, right?
this.props.form.handleChange (e);
this.props.form.handleBlur (e);