Keli
Keli

Reputation: 11

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>

Upvotes: 0

Views: 287

Answers (1)

Kummer Wolfe
Kummer Wolfe

Reputation: 603

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("");
    };
}

Upvotes: 0

Related Questions