简体   繁体   中英

How do I trigger HTML5 validation error popup when custom validation message is set manually?

I have the following code:

 document.getElementById('testSubmit').addEventListener('click', (e) => { e.preventDefault(); document.getElementById('test').setCustomValidity('THIS WILL ALWAYS BE AN ERROR, how do I display this message?'); console.log(document.getElementById('test').validationMessage); }); 
 <input id = "test" type = "email" required> <input id = "testSubmit" type = "submit"> 

As you can see, I can indicate that an error happens in the input field. However, I would like to display the message in my input.validationMessage which is set by setCustomValidity method in my error popup (which does not appear). How do I make the UI validation error popup to appear. For reference, the popup I'm referring to can be seen in the following code:

 document.getElementById('btn-submit').addEventListener("click", function() { if (!document.getElementById('form').checkValidity()) { document.getElementById("submit-hidden").click(); } }); 
 <form id="form" action=""> <input type="text" required /> <input id="submit-hidden" type="submit" style="display: none" /> </form> <button id="btn-submit">Submit</button> 

Which displays the popup 'Please fill out this field' when you submit without filling the field. How do I trigger that popup, but with my custom validation message?

You can do so by using the .reportValidity(). Here is an example:

 document.getElementById('testSubmit').addEventListener('click', (e) => { e.preventDefault(); document.getElementById('test').setCustomValidity('THIS WILL ALWAYS BE AN ERROR, how do I display this message?'); document.getElementById('test').reportValidity(); }); 
 <input id = "test" type = "email" oninput="validateInput();" required> <input id = "testSubmit" type = "submit"> 

You can you below code for Customize default validation message, But I have doning for required validation not for other, if you want to do for other validation as well please customize more

Form Code

<form action="" method="get">
    <input type="text" name="a" id="a">
    <input type="text" name="b" id="b" required>
    <button type="submit">Submit</button>
</form>

Js Code

document.addEventListener("DOMContentLoaded", function() {
    var elements = document.getElementsByTagName("input");
    for (var inp of elements) {
        inp.oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("Change Validation Message");
            }
        };
        inp.oninput = function(e) {
            e.target.setCustomValidity("");
        };
    }
})

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