How to change default “please fill out this field” in two field

后端 未结 4 755
无人共我
无人共我 2021-02-13 18:30

I would like two different messages in two field, for example, the username and password field that contain messages like \"username cannot be blank\" and \"password cannot be b

4条回答
  •  旧时难觅i
    2021-02-13 19:05

    You may add an id attribute to both your username and password input elements:

    
    
    

    Then you may use a switch statement to add the custom validation message according to the target of the event:

    $(document).ready(function () {
        var elements = document.getElementsByTagName("INPUT");
        for (var i = 0; i < elements.length; i++) {
            elements[i].oninvalid = function (e) {
                e.target.setCustomValidity("");
                if (!e.target.validity.valid) {
                    switch (e.srcElement.id) {
                        case "username":
                            e.target.setCustomValidity("Username cannot be blank");
                            break;
                        case "password":
                            e.target.setCustomValidity("Password cannot be blank");
                            break;
                    }
                }
            };
            elements[i].oninput = function (e) {
                e.target.setCustomValidity("");
            };
        }
    })
    

    Here's a demo.

提交回复
热议问题