简体   繁体   中英

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():

Here's the problem:

First I create an array of value and a form connected with a click event:

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.

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.

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. 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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