Del boy Del boy - 1 month ago 10
Javascript Question

Error message does not appear if input value is just blank space

If

input
value is empty my JS function returns
false
when I click on
submit
button. However if
input
is just blank space
" "
it's still returning
false
but the error message and
input text border color
do not showing up like they do when input value is empty
""
.

HTML

<form>
<input id="textbox" type="text" required/>
<input type="submit" id="btnSubmit" value="Save" />
</form>


JavaScript

var input = document.getElementById("textbox").value.trim();

if (input .length == 0) {

return false;
}

Answer

you need to use 'pattern' attribute and specify a regex expression for at least a single character.

Try

<input id="textbox" type="text" pattern="^\d*[a-zA-Z][a-zA-Z0-9]*$" required/>

The above pattern

  • Zero or more ASCII digits
  • One alphabetic ASCII character
  • Zero or more alphanumeric ASCII characters