Reputation: 529
I'm trying to validate the username and email with my express-app, but on the asyncValidate method, when i validate one, the other error state disappear.
const asyncValidate = (values, dispatch, props, field) => {
if (field === 'username') {
const url = config.dev_api_url + `/validation/username/${values.username}`
return axios.get(url).then(res => {
if (res.data.username === true) {
throw { username: 'Already exists' }
}
})
} else if (field === 'email') {
const url = config.dev_api_url + `/validation/email/${values.email}`
return axios.get(url).then(res => {
if (res.data.email === true) {
throw { email: 'Already exists' }
}
})
}
}
Here is the function where i render the input error.
renderInput = form => {
let fieldClasses = 'field fluid'
let inputClasses = 'ui fluid input '
let messageType = ''
let messageContent = ''
let iconType = ''
if (form.meta.error && form.meta.touched) {
messageType = 'error'
messageContent = form.meta.error
fieldClasses += ' error'
inputClasses += ' icon'
iconType = 'error'
if (form.meta.error === 'password_error') {
messageContent = (
<em>
<b>1 Uppercase</b> letter <br />
<b>1 Lowercase</b> letter <br />
<b>1 Number</b> <br />
At least <b>8 characters</b> long <br />
</em>
)
}
} else if (form.meta.touched) {
inputClasses += ' icon'
iconType = 'success'
}
return (
<div className={fieldClasses}>
<label>{form.label}</label>
<div className={inputClasses}>
<input {...form.input} autoComplete="off" type={form.type} placeholder={form.placeholder} />
{this.renderIcon(iconType)}
</div>
{this.renderMessage(messageType, messageContent)}
</div>
)
}
When i throw a new error, the other one disappears. here are some images.
Upvotes: 1
Views: 1213
Reputation: 467
I have found a not too dirty way to do it - in case anyone needs to use redux-form:
const asyncValidate = ( values, dispatch, props, field ) => {
let validationPromises = [
{
field: "field1",
request: axios.get(`validationUrl1/${values.field1}`),
error: "Error message 1"
},
{
field: "field2",
request: axios.get(`validationUrl2${values.field2}`),
error: "Error message 2"
}
]
let promisesResolved = validationPromises.map(promise => promise.request.catch(error => ({ error })));
return axios.all(promisesResolved).then(
(args) => {
let errors = {};
args.forEach( (r, idx ) => {
if(!r.error){
errors[validationPromises[idx].field] = validationPromises[idx].error
}
})
if(Object.keys(obj).length > 0){
throw errors
}
}
)
}
Upvotes: 2
Reputation: 529
This is gonna be brief.
Is a mess to do that with Redux-Form, so i better use Formik, is lighter, and just handle the necessary things, unless you need some features of redux-form, this is the way to go.
https://jaredpalmer.com/formik/docs/overview
Upvotes: 0