Search code examples
reactjsreduxredux-form

Validate async multiple fields redux-form


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.

img1

img2

img3


Solution

  • 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