不再需要必需的复选框来提交表单如果您不选中条款接受框,则可以提交

问题描述

我已经提交了自己的验证码来在提交信息之前检查模式和字段。不再需要提交所需的复选框(例如,注册表单上的条款接受复选框)。如果您不选中条款接受框,则可以提交并显示错误。但是,表单验证应该失败并且不应提交表单。则该复选框应以必需的方式显示,以可视方式指示是否存在错误(即红色边框)(如果需要且未选中)。

#standardsql
SELECT
  COUNT(event_name) AS total_events,COUNTIF(event_name = 'visited x page') AS goal
FROM `project.dataset.table`

上面的代码是我遇到的表单,表单提交(带有Enter或单击提交时)而没有检查复选框是否被选中

<article id="clients_add">
                <form method="POST" action="/client/invite">
                    <input type="tel" name="phone" placeholder="Phone Number" pattern="^[0-9\-\+\s\(\)]*$" required="required" />
                    <input type="text" name="email" placeholder="E-mail Address" pattern="^[^@]+@[^@]+\.[^@]+$" required="required" />
                    <input type="checkBox" required="required" id="contactclient" name="contactclient" value="1" />
                    <label for="contactclient">
                        <span><strong>&#10004;</strong></span>
                        Client agreed to be contacted.
                    </label>
                    <input type="submit" value="Invite" />
                </form>
            </article>

//功能扩展

(function ($) { // grabs a HTML element
// $.validator (target) - makes it possible to not show the error when a required field is empty until the form is submitted
$.validator = function (target) {

   // if any key is pressed,released or it has lost focus then:
    $(document).on ("keydown keyup blur",target,function (event) {
        if (!$(this).is ("textarea")) { // if this is NOT textArea element
            let code = event.keyCode || event.which; // check which was pressed
            if(code === 13) {  // if ENTER key was pressed then:
                event.preventDefault (); // DOES NOT TRIGGER Default action
                event.stopPropagation (); // prevent any other handler from being notified
                if (event.type === 'keyup') { // once the key is released(if there is a released key)
                    $(this).closest ("form").trigger ("submit");// travel to the closest form and execute submit
                }
                return false; //return this to validator.js
             }
        }
        let valid = true; // assume it is valid (textarea element at this point)
        if ($(this).val ().length > 0)  // if the value entered has more than 0 characters
            $(this).attr ("data-empty",null); // change data-empty attribue to null (since it has more than 0 characters)
        //if the element IS required(set) and the data-empty attribute IS NOT DEFINED
        if (typeof $(this).attr ('required') != 'undefined' && typeof $(this).attr ('data-empty') == 'undefined') {
            if ($(this).val ().length === 0) { // and if there is nothing written down
                valid = false; // is NOT Valid
            }
        }
        // As long as the element specifies ANY kind of pattern then:
        if (typeof $(this).attr ('pattern') != 'undefined') {
            //IF the pattern we are looking for of the element is NOT found and the data empty attribute of the element is NOT defined
            if ($(this).val ().search (new RegExp ($(this).attr ("pattern"))) === -1 && typeof $(this).attr ('data-empty') == 'undefined') {
                valid = false;  //is NOT valid
            }
        }
        if (valid) { // if it is still valid after all the hurdles then:
            $(this).siblings ("span.error").removeAttr ('style'); // all the siblings prone to "span.error" remove the style attribute
            $(this).removeClass ("invalid"); // remove invalid class of the element
        } else {
            $(this).siblings ("span.error").css ('visibility','visible'); //make all the siblings span.error css visible
            $(this).addClass ("invalid"); // add invalid class to element
        }
    });


    // if an element receives a click,or a value of an element has been changed from input types:radio and checkBox
    $(document).on ("click","form input[type='checkBox'],form input[type='radio']",function (event) { //event parameter for what?????
        if ($(this).attr("checked") && $(this).attr ("type") === "checkBox") { //if this IS a checkBox input type and it is checked
            $(this).attr ("checked",null); // change the value to null ( same as .removeAttr())
            $(this).addClass ("unchecked"); // add unchecked class to the element
            $(this).removeClass ("checked"); // remove checked class from the element
            $(this).removeClass ("invalid"); //remove invalid class from the element
        }
        else {
            if ($(this).attr ("type") === "radio") { // if it is a radio type input
                $("input[name='" + $(this).attr ("name") + "']").attr ("checked",null);
                $("input[name='" + $(this).attr ("name") + "']").addClass ("unchecked");
                $("input[name='" + $(this).attr ("name") + "']").removeClass ("checked");
                $("input[name='" + $(this).attr ("name") + "']").removeClass ("invalid");
            }

            $(this).attr ("checked","checked"); //either way check change the checked attribute to checked ????
            $(this).addClass ("checked"); // add checked class to either element
            $(this).removeClass ("unchecked"); // remove unchecked class from the element
            $(this).removeClass ("invalid"); // remove invalid class from the element
        }
        return false; //return false to validator.js
    });

    // if an element is clicked or a key is pressed or released
    $(document).on ("keydown keyup click","form label[for]",function (event) {
        let code = event.keyCode || event.which; //listen to the type of key pressed

        // if the event is a click and the targeted event is "a"    OR     the key pressed is SPACE KEY
        if ((event.type === "click" && !($(event.target).is("a"))) || (event.type === "keydown" && code === 32)) {
            $("input[id='" + $(this).attr ("for") + "']").click ();
            return false;


            //IF the key pressed is enter
        } else if (event.type === "keyup" && code === 13) {
            $(this).closest ("form").trigger ("submit");
            return false; // Return false to validator js
        }
        return true;  // validation success
    });



    //when the element is being pressed with the pointing device on a input submit button
    $(document).on ("mousedown","input[type='submit']",function (event) {
        event.preventDefault (); //cancels default event
        event.stopPropagation (); // stops bubbling up to parent elements or capturing down to child elements
        $(this).closest ("form").trigger ("submit"); // trigger submit on the form
        return false;      //return false to validator. js
    });

    // Whenever a FORM is submitted
    $(document).on ("submit","form",function (event) {
        // lets grab the form
        let form = $(this); //jquery this = element (form)
        form.attr ("data-valid","false"); // SET the data-valid attribute to false
        form.find ("[data-empty]").each (function () { // find any elements where the data-empty attribute exist' and for each of them:
            $(this).attr ('data-empty',null); // set the attribute (data-empty) to null
        })

        let valid = true;  // let's assume it is valid

        console.log (new Date().getTime () + ' formValidation start'); // start of the debug session
        console.log (new Date().getTime () + ' formValidation checking disabled'); //

        // If the disabled attribute of the element(input[type='submit']) in the form is defined OR the disabled attribute of the input[type='submit'] in the form is false
        if (!(typeof form.find ("input[type='submit']").attr ("disabled") == 'undefined' || form.find ("input[type='submit']").attr ("disabled") === 'false')) {
            console.log (new Date().getTime () + ' formValidation submit disabled'); // REPORT THAT THE FORM VALIDATION IS disABLED
            valid = false;  //return false to the validator
        }
        console.log (new Date().getTime () + ' formValidation checking required'); // report that the formValidation checking is required

        form.find ("*[required]").each (function () {       // for each required element in the form
            console.log (new Date().getTime () + ' formValidation required ' + $(this).attr ("name")); // OUTPUT that formvalidation is required for: "name"
            //if the required attribute of the element  is NOT FALSE (IN FACT A required ELEMENT)
            if ($(this).attr ("required") !== 'false') {
                //and If the type attribute is RAdio
                if ($(this).attr ("type") === "radio") {
                    //and if the
                    if ($("input[name='" + $(this).attr ("name") + "'].checked,input[name='" + $(this).attr ("name") + "']:checked").length === 0) {
                        valid = false;
                        console.log (new Date().getTime () + ' formValidation required fail');
                        $(this).siblings ("span.error").css ('visibility','visible');
                        $(this).addClass ("invalid");
                    }

                    //else if the type attribute is a checkBox
                } else if ($(this).attr ("type") === "checkBox") {
                    // and if the element has a class called "checked" and the element is actually checked
                    if (!$(this).hasClass ("checked") && !$(this).is(":checked")) {
                        valid = false; // validation is false
                        console.log (new Date().getTime () + ' formValidation required fail');  //report validation
                        $(this).siblings ("span.error").css ('visibility','visible');// get the siblings that can "span.error" and make the visibility visible
                        $(this).addClass ("invalid"); // also add invalid class to the element
                    }
                    //else if the element value(textarea perhaps,input) is EXACTLY 0
                } else if ($(this).val ().length === 0) {
                    valid = false; // make it INVALID
                    console.log (new Date().getTime () + ' formValidation required fail'); // Output validation
                    $(this).siblings ("span.error").css ('visibility','visible'); // for all the siblings elements that share span.error selector make the span error visible
                    $(this).addClass ("invalid"); //also add the invalid class
                }
            }
        });
        //
        console.log (new Date().getTime () + ' formValidation checking pattern');// Output checking pattern
        form.find ("*[pattern]").each (function () { // for each element with a pattern attribute
            console.log (new Date().getTime () + ' formValidation pattern ' + $(this).attr ("name") + ' ' + $(this).attr ("pattern"));//output the pattern and the name
            //if this element does not comply with pattern attribute (prevIoUsly established)
            if ($(this).val ().search (new RegExp ($(this).attr ("pattern"))) === -1) { //
                valid = false; // then is not Valid
                console.log (new Date().getTime () + ' formValidation pattern fail');      // output validation issue
                $(this).siblings ("span.error").css ('visibility','visible'); // make all span error siblings (selector) visible
                $(this).addClass ("invalid"); // add invalid class
            }
        });

        //ASSUMING IT IS VALID
        if (valid) {
            form.attr ("data-valid","true");  // set the data-valid attribute to true
            form.find ("input[type='submit']").attr ("disabled","disabled"); // find in the form with the selector (input[type='submit']) where the disabled attribute set to disabled
            form.find ("input[type='checkBox']").each (function () { // find the input checkBoxes in the form and for each
                //if the element has a class called checked
                if ($(this).hasClass ("checked")) {
                    //nothing because it is checked
                }
                else if ($(this).hasClass ("unchecked")) { // if the element has a class called uncheked
                    $(this).attr ('value',''); // set the value to ''

                }
                else if ($(this).is (":checked")) { // if this is :checked then:
                    //nothing because it is checked
                }
                //for everything else make the value empty
                else {
                    $(this).attr ('value','');
                }

                $(this).attr ('type','hidden'); // set the element attribute type to hiddent
            });

            form.find ("input[type='radio']").each (function () { // for each input that type is radio do the following
                //check if the radio input has a checked class OR
                if ($(this).hasClass ("checked") || ($("input[name='" + $(this).attr ("name") + "'].checked").length === 0 && $(this).is (":checked"))) {
                    $(this).attr ("type","hidden"); // set the type value of the radio input to hiddent
                    return false;  //return false
                }
            });
            // look for the button of type radio  and remove it
            form.find ("input[type='radio']").remove ();
            href = window.location.href;
            window.location.hash = 'coming';
            window.history.replaceState (form.serializeArray (),document.title,href);
        } else {
            event.preventDefault ();
            event.stopPropagation ();
        }
        return valid;           
    });
}

})(jQuery);

上面的代码是我所做的验证。我评论了一些内容,以使其更易于阅读和理解其背后的逻辑

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)