0

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>
xKobalt
  • 1,498
  • 2
  • 13
  • 19
Keli
  • 11
  • 3
  • I believe this has been answered here. Take a look: https://stackoverflow.com/questions/5272433/html5-form-required-attribute-set-custom-validation-message – Kummer Wolfe Feb 28 '20 at 12:26
  • I have tried this already but it will replace blank field validator and show only custom message even if box is empty or with white space. – Keli Feb 28 '20 at 12:37

1 Answers1

0

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("");
    };
}
Kummer Wolfe
  • 603
  • 5
  • 13