Home > Software engineering >  Javascript validation works...and fails
Javascript validation works...and fails

Time:08-20

I have the following Javascript code in my web page that SHOULD ensure data validation and then (if the form is valid) submit the data to an AJAX call:

    <script>
        $(document).ready(function () {
            $("#frmInfo").submit(function (event) {
                event.preventDefault();
                var forms = document.getElementsByName('frmInfo');
                var validation = Array.prototype.filter.call(forms, function (form) {
                    if (form.checkValidity() == false) {
                        form.classList.add('was-validated');
                        alert('Hit invalid user input');
                        return false;
                    }
                    else {
                        alert('Everything is valid');
                        form.classList.add('was-validated');
                    }
                });

                var obj = Object.fromEntries(new FormData(event.target));
                if (obj.Is_Body_HTML == 1)
                    obj.Is_Body_HTML = true;
                else
                    obj.Is_Body_HTML = false;
                if (obj.Is_Active == 1)
                    obj.Is_Active = true;
                else
                    obj.Is_Active = false;

                setDisabled();
                var json = JSON.stringify(obj);
                alert(json);
                var request = $.ajax({
                    url: "../handlers/test.ashx",
                    method: "POST",
                    data: json,
                    dataType: "json"
                });
                request.done(function (msg) {
                    if (msg.Success == false) {
                        $('#infoErr').html('Should not have reached this!');
                        $('#toastInfoFail').toast('show');
                    }
                    else {
                        localStorage.setItem('cust_no', msg.ID);
                        document.location.href = 'getaddress.aspx';
                    }
                });
                request.fail(function (jqXHR, textStatus) {
                    $('#infoErr').html('Unable to contact server to process change request.  Please try again later.');
                    $('#toastInfoFail').toast('show');
                });
                request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
                    setEnabled();
                });
            });

            $('#BestTelephone').inputmask("999-999-9999");
            $('#FirstName').focus();
        });

        function setDisabled() {
            $('#btnNext').prop('disabled', true);
        }

        function setEnabled() {
            $('#btnNext').prop('disabled', false);
        }


    </script>

The problem is, the validation works, but it doesn't. When the form fields are not valid, it hits this block:

if (form.checkValidity() == false) {
    form.classList.add('was-validated');
    alert('Hit invalid user input');
    return false;
}

and the alert is displayed. The very next line should force the function to exit, stopping execution of any remaining code, but for some reason it doesn't. Instead, the remainder of the code executes as if the form is valid, and the alert for the AJAX failure pops up.

Why does the 'return false' not actually force the function to exit, and what am I missing here?

CodePudding user response:

return false is a statement of the anonymous function function (form) {... which is called for each form element. The anonymous function function (event) {... doesn't have a return statement. The filter function in Array.prototype.filter.call(forms, has to return either true or false for each element to work as expected, not false or undefined. You could use e.g. Array.prototype.every and/or Array.prototype.map instead of Array.prototype.filter:

<script>
    $(document).ready(function () {
        $("#frmInfo").submit(function (event) {
            event.preventDefault();
            var forms = document.getElementsByName('frmInfo');
            var validation = Array.prototype.map.call(forms, function (form) {
                if (!form.checkValidity()) {
                    form.classList.add('was-validated');
                    alert('Hit invalid user input');
                    return false;
                }
                else {
                    alert('Everything is valid');
                    form.classList.add('was-validated');
                    return true;
                }
            });
            if (!validation.every(el => el)) return false;
            var obj = Object.fromEntries(new FormData(event.target));
            if (obj.Is_Body_HTML == 1)
                obj.Is_Body_HTML = true;
            else
                obj.Is_Body_HTML = false;
            if (obj.Is_Active == 1)
                obj.Is_Active = true;
            else
                obj.Is_Active = false;

            setDisabled();
            var json = JSON.stringify(obj);
            alert(json);
            var request = $.ajax({
                url: "../handlers/test.ashx",
                method: "POST",
                data: json,
                dataType: "json"
            });
            request.done(function (msg) {
                if (msg.Success == false) {
                    $('#infoErr').html('Should not have reached this!');
                    $('#toastInfoFail').toast('show');
                }
                else {
                    localStorage.setItem('cust_no', msg.ID);
                    document.location.href = 'getaddress.aspx';
                }
            });
            request.fail(function (jqXHR, textStatus) {
                $('#infoErr').html('Unable to contact server to process change request.  Please try again later.');
                $('#toastInfoFail').toast('show');
            });
            request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
                setEnabled();
            });
        });

        $('#BestTelephone').inputmask("999-999-9999");
        $('#FirstName').focus();
    });

    function setDisabled() {
        $('#btnNext').prop('disabled', true);
    }

    function setEnabled() {
        $('#btnNext').prop('disabled', false);
    }


</script>
  • Related