简体   繁体   English

如何使用检查有效性来通过jquery验证表单

[英]How to use check validity to validate a form with jquery

I'm trying to debug a snippet, so I can understand how it works the native javascript validation checkValidity(): 我正在尝试调试代码段,因此我可以了解它是如何工作的本机javascript验证checkValidity():

Here's the problem: 这是问题所在:

First I create an array of value and a form connected with a click event: 首先,我创建一个值数组和一个与click事件相关的表单:

jQuery('input[name="submit-request-form"]').click(function() {
    var fields = [ 'FirstName','Lastname','Email','Telephone','CampusID','ProgramID'];
    var form = 'flow-request-form';
    disableSubmitButton( $(this) , fields , form );

});

The next step is to create a function in order to get all the elements in the form based on my array and if all of them are filled, change the value valid to false and submit the form. 下一步是创建一个函数,以便基于我的数组获取表单中的所有元素,如果所有元素都已填充,请将有效值更改为false并提交表单。

function disableSubmitButton( Obj , fields , form ){

    var valid = true;
    for (var i = 0 ; i < fields.length ; i++) {
        var element = jQuery('form[name="'+form+'"] [name="'+fields[i]+'"]');
        console.log( element[0].checkValidity());
        if( element[0] && !element[0].checkValidity() ){
            valid = false;
            break;
        }
    }
    console.log(valid);
    if(valid){
        Obj.attr('disabled' , 'disabled');
    }
}

In case the value of my form will be not filled or invalid, the valid variable won't change to false and it will disable the button. 如果我的表单的值不会被填充或无效,则有效变量将不会更改为false并将禁用该按钮。

Something though got wrong and my value will always be true. 虽然出了点问题,但我的价值永远是对的。

Do someone knows why? 有人知道为什么吗?

The snippet is the following: 该代码段如下:

if( element[0] && !element[0].checkValidity() ){
    valid = false;
    break;
}

that's where my code fails 那是我的代码失败的地方

You could use form.reportValidity() for that. 您可以为此使用form.reportValidity()。 It basically checks the form and validates it, and if it detects an invalid field, it will return a popup message. 它基本上检查表单并验证它,并且如果它检测到无效字段,它将返回一个弹出消息。

 trackedInput = $('#trackedInput'); confirmSubmit = $('#confirmSubmit'); yourForm = document.querySelector('#confirm'); confirmSubmit.click(function(e) { yourForm.reportValidity(); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="hidden"> <input id="trackedInput" type="text" form="confirm" required> </div> <div class="hidden"> //Some other stuffs here </div> <div class="not_hidden"> <input id="confirmSubmit" type="submit" form="confirm" required> </div> <form id="confirm"></form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM