horprogs / Just-validate

Modern, simple, lightweight (~5kb gzip) form validation library written in Typescript, with no dependencies (no JQuery!). Support a wide range of predefined rules, async, files, dates validation, custom error messages and styles, localization. Support writing custom rules and plugins.

Home Page:https://just-validate.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

validateBeforeSubmitting doesn't allow triggering async validator

bepenelle opened this issue · comments

I set validateBeforeSubmitting to true. Thanks to that settings, the synchronous validators do trigger when the field value changes. However, my async validator is not triggered when the field value changed.

Here is my code :

$(function(){
    const validation = new JustValidate('#signupForm', {
        validateBeforeSubmitting: true,
    });

    validation
        .addField('#pseudo', [
            {
                rule: 'required',
                errorMessage: 'Field is required'
            },
            {
                rule: 'minLength',
                value : 3,
                errorMessage: 'Minimum 3 characters'
            },
            {
                rule: 'maxLength',
                value : 16,
                errorMessage: 'Maximum 16 characters'
            },
            {
                validator: function(value) {
                    return function() {
                        return $.getJSON("member/pseudo_available_service/" + value);
                    }
                },
                errorMessage: 'Name already exists',
            },
        ], { successMessage : 'Looks good !'})
        ...

How can I solve this ?

Async validators not triggered after inputs changing (this applies to validateBeforeSubmitting as well). The reason is you usually don't want to call API endpoints for every change, it creates unnecessary load for the backend.

Currently async validators triggered only when you submit the form.

I can suggest a workaround to use onValidate callback (it triggered every time when input changes), call your endpoint there and use showErrors method

Is there a workaround? This is some kind of feature request in my case. It should be nice to have a flag in the settings for that and let the developer decide if the extra load is acceptable or not.

yeah makes sense to add this flag. I described a workaround above

thanks, I will try the workaround

looking forward for the flag in the settings ;-)

The workaround you proposed works great! Thx

.onValidate(async function(event) {
    const res = await $.getJSON("member/pseudo_available_service/" + $("#pseudo").val());
    if (!res)
        this.showErrors({ '#pseudo': 'The pseudo is already used' })
})

However, if you manage to add a flag in the settings to handle that use case in a more "standard" way, I'm most certainly interested.

commented

Any update, eta on this issue?