简体   繁体   中英

Custom validity input box html

I am trying to create a form with the input type text box with two conditions.
1 ) validate empty field.
2 ) white space not allowed.
I have added pattern, everything is working fine when empty box, it says Please fill the empty field , and when user puts space in the username it says Please match the format requested , but the problem is that I am trying to replace default Please match the format requested with White space not allowed . But I am unable to find any solution anywhere.

My code is listed below:

<form method="post">
<input type="text" name="username" pattern="\S+" required >
</form>

You'll need to add client side code to support what you're wanting to do with setCustomValidity with a check against the value it found. Like so:

    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) {
                if ( e.target.value.match(/[\s\t]+/i) ) {
                e.target.setCustomValidity("White space not allowed");
            } else {
                e.target.setCustomValidity("This field cannot be left blank");
            }

        }
    };
    elements[i].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