Validating Input at the Client: Check for blank or required fields

Written by:  • Edited by: Linda Richter
Published Sep 30, 2008
• Related Guides: Javascript | CPU

Checking for blank or required fields and preventing form submission or further processing can be accomplished in DHTML with DOM and JavaScript methods , properties and events.

Introduction

The code below is for a text input field, a submit button and a DIV tag that we could use in lieu of an alert box for notifying the user that the input field is required. The code uses the onblur event to determine if the input box is blank and notify the user that this is a required field.

Note: The style properties in this example are set for convenience but are not required.

Code view

Username&nbsp;<input name="userName" type="text" id="userName" style="display:block;margin-top:5px;margin-bottom:5px;" onblur=''" />

<input name="submit" type="submit" id="submit" style="display:block;" value="submit"/>

<div id="messageDiv" style="margin:5px;"></div>

Set the onBlur

Case 1: in the tag code

Here we don't need a script block. Instead, the JavaScript code is written right in the onblur attribute of the text input tag definition.It may be difficlut to see but this is the string:

..onblur=' if(this.value=="")

{this.focus();this.style.background="lightyellow";

document.getElementById("messageDiv").innerHTML=this.id+" is a required field!"} '

Code view

Username&nbsp;<input name="userName" type="text" id="userName" style="display:block;margin-top:5px;margin-bottom:5px;" onblur='if(this.value==""){this.focus();this.style.background="lightyellow";document.getElementById("messageDiv").innerHTML=this.id+" is a required field!"}' />

<input name="submit" type="submit" id="submit" style="display:block;" value="submit"/>

<div id="messageDiv" style="margin:5px;"></div>

Showing page 1 of 2

 
blog comments powered by Disqus
Email to a friend