JSFiddle - React, Tailwind, and code Playground

by konijn_gmail_com

HTML

<form id="myForm">
    <h2>My Test Form!</h2>
      <div id="nag"></div>
    <label>First Name</label>
    <input type="text" class="mandatory" />
    <br />
    <label>Middle Name</label>
    <input type="text" class="short" maxlength="1" />
    <br />
    <label>Last Name</label>
    <input type="text" class="mandatory" />
    <br />
    <button type="button" onclick="validate('myForm','mandatory'); return false">
      Validate
    </button>
  </form>

CSS

.short { width : 20px ; }
.mandatory{ background-color : Khaki ; }
label { width : 100px;   float:left; }
#nag { font-weight : bold; color: FireBrick  }

JavaScript

//Search for all mandatory fields, point out that they are not filled in
function validate( formID , className )
{
  var form = document.getElementById( formID ),
      elements = form.getElementsByClassName( className ),
      i;
  
  //It is possible that there are no mandatory fields
  if( !elements || !elements.length )
    return
    
  //We are counting on smart developers, who only apply the mandatory class
  //to text boxes.
  for( i = 0 ; i < elements.length; i++ )      
  {
    var element = elements[i];
    if( !element.value )
    {
      nagUser( element )
      //informUser( element );
      element.focus();      
      return;
    }
  }

}
/*  Tell the user what to do */
function nagUser( element )
{
  var nagElement = document.getElementById( "nag" );
  nagElement.textContent = "Please fill in the " + findLabel( element );
}

/* Dont tell the user to fill in a field if (s)he did */
function stopNagging()
{
  var nagElement = document.getElementById( "nag" );
  nagElement.textContent = "";    
}

/* Old Skool alert, can be annoying to the user */
function informUser( element )
{
  alert( "Please fill in the " + findLabel( element ) );
}

/* Find a matching label for a given input box, return "field" if nothing is found */
function findLabel( element )
{
  while( element && element.localName != "label" )
      element = element.previousSibling;
  return element.textContent || "field";
}    

/* This makes the nagging stop when the user exits an inputbox that is filled in */
var inputBoxes = document.getElementsByTagName( "input" );
for( var i = 0 ; i < inputBoxes.length ; i++ )
{
  var inputBox = inputBoxes[i];
    inputBox.addEventListener( "blur" , function(e)
    {
        if( this.value )
          stopNagging();    
    });
}