Caelan Grgurovic Caelan Grgurovic - 5 months ago 7x
Javascript Question

Username Length Verification jQuery

I am attempting to create jQuery form which is automatically updated every time the user clicks.

At the moment I am working on querying if the username is correct length; if it is not, it will make the input box outlined red.

This is my current code (which does not seem to function at all).


<script src=""></script>
<script type="text/javascript">
jQuery(function($) {
$(document).click(function(e) {
if (!$('#jq-user-getval').length) {
if ( $('#jq-user-getval').val() != '' ) {
if( $("#jq-user-getval").val() < 4) {

as you can see, I have made it so that when the user clicks away from the input box, it will check if the box is empty. If it is empty, it will check if the length is less than 4 characters, then it is supposed to add a class forcing the red outline. This is not working, however.

this is the HTML, I am unsure if the problem lies here or not:

<form action="" method="post">
<input id="jq-user-getval jq-user-class" type="text" name="username">

I am trying to replicate Microsoft's "Hotmail" registration form, if you can suggest any changes.


Your id value is incorrect. Technically, id cannot contain spaces. Change your <input /> to:

<input id="jq-user-getval" class="jq-user-class" type="text" name="username" />

The way you are using .val() < 4 is also wrong. You cannot compare like that with a string:

"hello" < 4;         // This is meaningless.
"hello".length < 4;  // You should use this.

Use .blur() function for this:

$(function () {
  $("#jq-user-getval").blur(function () {
    if (this.value.trim().length !== 0 && this.value.trim().length < 4)

If you are dynamically loading the <input />, then you can delegate the event this way:

$(function () {
  $(document).on("blur", "#jq-user-getval", function () {
    if (this.value.trim().length !== 0 && this.value.trim().length < 4)

I have added .trim() for extra security, like people might get away putting spaces.

There's no real reason for you to use the .click() function anywhere here. The clicking away really triggers blur event on the <input />.