Trigger standard HTML5 validation (form) without using submit button?

前端 未结 12 1423
攒了一身酷
攒了一身酷 2020-11-28 07:07

Anyone who know how I can trigger the standard HTML5 validation in a form without using a submit button? (JavaScript or jQuery).

I do not want to se

12条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 07:55

    After some research, I've came up with the following code that should be the answer to your question. (At least it worked for me)

    Use this piece of code first. The $(document).ready makes sure the code is executed when the form is loaded into the DOM:

    $(document).ready(function()
    {
        $('#theIdOfMyForm').submit(function(event){
            if(!this.checkValidity())
            {
                event.preventDefault();
            }
        });
    });
    

    Then just call $('#theIdOfMyForm').submit(); in your code.

    UPDATE

    If you actually want to show which field the user had wrong in the form then add the following code after event.preventDefault();

    $('#theIdOfMyForm :input:visible[required="required"]').each(function()
    {
        if(!this.validity.valid)
        {
            $(this).focus();
            // break
            return false;
        }
    });
    

    It will give focus on the first invalid input.

提交回复
热议问题