chiefwigms / picobrew_pico

MIT License
149 stars 63 forks source link

Form validation for new pico recipe fails based on values entered #339

Closed trmong closed 2 years ago

trmong commented 2 years ago

In the file app/static/js/pico_recipe.js the validate(form) function fails depending on the values entered. Because of the logic it can fail because some of the min values for "numbers" are set to 0 in the html file. In addition the logic is comparing strings not floating point values. This can cause variable logic results. It can be fixed by using the parseFloat() function to properly convert the values before comparison.

Here is the original code:

 function validate(form) {
    let valid = true;
    for (element of form.getElementsByTagName('input')) {
        const $feedback = $(element).siblings(".invalid-feedback", ".invalid-tooltip");
        if (element.type == "text" && element.pattern) {
            const re = new RegExp(element.pattern)
            if (!re.test(element.value)) {
                $feedback.show();
                valid = false;
            }
        }

        if (element.type == "number" && (element.min || element.max)) {
            if ((element.min && element.value < element.min) || (element.max && element.value > element.max)) {
                $feedback.show();
                valid = false;
            }
        }
    };

    $(form).addClass("was-validated");
    return valid;
 }

Here is my proposed solution that fixes the issues I had....

 function validate(form) {
    let valid = true;
    for(element of form.getElementsByTagName('input')) {
        const $feedback = $(element).siblings(".invalid-feedback", ".invalid-tooltip");
        if ( element.type == "text" && element.pattern ) {
            const re = new RegExp(element.pattern)
            if ( !re.test(element.value) ) {
                $feedback.show();
                valid = false;
                break;
            }
        } else if ( element.type == "number" ) {
            if ( element.min != "" ) {
                if ( parseFloat(element.value) < parseFloat(element.min) ) {
                    $feedback.show();
                    valid = false;
                    break;
                }
            }
            if ( element.max != "" ) {
                if ( parseFloat(element.value) > parseFloat(element.max) ) {
                    $feedback.show();
                    valid = false;
                    break;
                }
            }
        }
    };

    $(form).addClass("was-validated");
    return valid;
}

Thanks

Tab

chiefwigms commented 2 years ago

duplicate to #338