cferdinandi / validate

A lightweight form validation script.
MIT License
230 stars 39 forks source link

Add a disabled attribute to the submit when not validated? #39

Closed shornuk closed 6 years ago

shornuk commented 6 years ago

Just started playing with the plugin. Really nice, thanks.

I'm using the disableSubmit: true to stop the form being submitted if not validated. Is there a way to pass a disabled attribute to the submit input when it's not validated? Functionally it work, bit it would just be nice to provide a visual indicator that the form cannot be submitted.

Unless I'm missing a way to do this already?

mwickett commented 6 years ago

I was just about to ask the same question...

cferdinandi commented 6 years ago

It does not, but I certainly could add a callback to support something like this.

cferdinandi commented 6 years ago

Just dug into the code a bit more, and I think this is actually, for simplicity of the core codebase and maximum flexibility for all use cases, supported by the existing callback methods.

Here's an example:

var toggleFormSubmit = function (field) {

    // Get the form for the field
    // You could also just target it directly
    // This is abstracted for multiple forms
    var form = field.closest(field);

    // Get the submit button
    var submit = form.querySelector('button[type="submit"]');
    if (!submit) return;

    // Check if there are any fields with errors
    var errors = form.querySelectorAll('input.error, select.error, textarea.error');

    // If there are errors, disable the submit button
    // Otherwise, enable it
    if (errors.length > 0) {
        submit.setAttribute('disabled', 'disabled');
    } else {
        submit.removeAttribute('disabled');
    }

};

validate.init({
    afterShowError: function (field, error) {
        toggleFormSubmit(field);
    },
    afterRemoveError: function (field) {
        toggleFormSubmit(field);
    },
});
shornuk commented 6 years ago

Looks good to me. Thanks for adding the example.

cferdinandi commented 6 years ago

Excellent!