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

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

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

#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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-