w3resource

JavaScript Field Level Form Validation using a registration form

Description

In this document, we have discussed JavaScript field level form validation on a sample registration form. Following pictorial shows in which field, what validation we want to apply.

form validartion field level

How would we set those validations

We have created JavaScript functions (one for each input field whose value is to be validated) which check whether a value submitted by user passes the validation.

It sets and keeps the focus on the input field until the user supplies a valid value.

When the user does so, they may proceed and can supply value to the next available field.

The later JavaScript function created is called on onsubmit event of the form.

HTML Code of the Sample Registration Form

<!DOCTYPE html>
<html lang="en"><head> <meta charset="utf-8"> <title>JavaScript Field Label Form Validation using a registration form</title> <meta name="keywords" content="example, JavaScript Form Validation, Sample registration form" /> <meta name="description" content="This document is an example of JavaScript Field label form validation using a sample registration form. " /> <link rel='stylesheet' href='js-field-level-form-validation.css' type='text/css' /> <script src="field-level-sample-registration-form-validation.js"></script> </head> <body onload="firstfocus();"> <h1>JavaScript Field Label Form Validation using a registration form</h1> <h2>Use tab key or mouse to go next field</h2>
<form name='registration'"> <ul> <li><label for="userid">User id [5 to 12 characters] :</label></li> <li><input type="text" name="userid" size="12" onblur="userid_validation(5,12)"/></li> <li><label for="passid">Password [7 to 12 characters] :</label></li> <li><input type="password" name="passid" size="12" onblur="passid_validation(7,12)"/></li> <li><label for="username">Name [Alphabates characters] :</label></li> <li><input type="text" name="username" size="50" onblur="allLetter()"/></li> <li><label for="address">Address [alphanumeric characters] :</label></li> <li><input type="text" name="address" size="50" onblur="alphanumeric()"/></li> <li><label for="country">Country [Must select a country] :</label></li> <li><select name="country" onblur="countryselect()"> <option selected="" value="Default">(Please select a country)</option> <option value="AF">Australia</option> <option value="AL">Canada</option> <option value="DZ">India</option> <option value="AS">Russia</option> <option value="AD">USA</option> </select></li> <li><label for="zip">ZIP Code [numeric characters] :</label></li> <li><input type="text" name="zip" onblur="allnumeric()"/></li> <li><label for="email">Email [Valid email] :</label></li> <li><input type="text" name="email" size="50" onblur="ValidateEmail()" /></li> <li><label id="gender">Sex [Select Male or Female] :</label></li> <li><input type="radio" name="sex" value="Male" checked /><span>Male</span></li> <li><input type="radio" name="sex" value="Female" /><span>Female</span></li> <li><label>Language [Optional] :</label></li> <li><input type="checkbox" name="en" value="en" checked /><span>English</span></li> <li><input type="checkbox" name="nonen" value="noen" /><span>Non English</span></li> <li><label for="desc">About [Optional] :</label></li> <li><textarea name="desc" id="desc"></textarea></li> <li><input type="submit" name="submit" value="Submit" onclick="alert('Form submitted successfully')" /></li> </ul> </form> </body> </html>

field-level-sample-registration-form-validation.js is the external JavaScript file which contains the JavaScript ocde used to validate the form.js-field-level-form-validation.css is the stylesheet containing styles for the form.

For the sake of demonstration, we have taken five countries only. You may add any number of countries in the list.

CSS Code of the Sample Registration Form

 h1{
  margin-left: 50px;
  color: navy;
  }
 h2{
  margin-left: 50px;
  color: navy;
  margin-top: -20px;
  }
  form li{
  list-style: none;
  margin-bottom: 5px;
  }
  form ul li label
  {
  float: left;
  clear: left;
  width: 265px;
  text-align: right;
  margin-right: 10px;
  font-family:Verdana, Arial, Helvetica, sans-serif;
  font-size:14px;
  }
 form ul li input, select, span 
  {
  float: left;
  margin-bottom: 10px;
  border: 1px solid maroon;
  }
  form textarea 
  {
  float: left;
  width: 350px;
  height: 150px;
  }
 [type="submit"] 
 {
  clear: left;
  margin: 20px 0 0 300px;
  font-size:18px
  }

JavaScript code for validation.

JavaScript functions called on onblur events of the each of the inputs in question

// After form loads focus will go to User id field.
  function firstfocus()
  {
  var uid = document.registration.userid.focus();
  return true;
  }
// This function will validate User id.
  function userid_validation(mx,my)
  {
  var uid = document.registration.userid;
  var uid_len = uid.value.length;
  if (uid_len == 0 || uid_len >= my || uid_len < mx)
  {
  alert("User Id should not be empty / length be between "+mx+" to "+my);
  uid.focus();
  return false;
  }
  // Focus goes to next field i.e. Password.
  document.registration.passid.focus();
  return true;
  }
// This function will validate Password.
  function passid_validation(mx,my)
  {
  var passid = document.registration.passid;
  var passid_len = passid.value.length;
  if (passid_len == 0 ||passid_len >= my || passid_len < mx)
  {
  alert("Password should not be empty / length be between "+mx+" to "+my);
  passid.focus();
  return false;
  }
  // Focus goes to next field i.e. Name.
  document.registration.username.focus();
  return true;
  }
// This function will validate Name.
  function allLetter()
  { 
  var uname = document.registration.username;
  var letters = /^[A-Za-z]+$/;
  if(uname.value.match(letters))
  {
  // Focus goes to next field i.e. Address.
  document.registration.address.focus();
  return true;
  }
  else
  {
  alert('Username must have alphabet characters only');
  uname.focus();

  return false;
  }
  }
  // This function will validate Address.
  function alphanumeric()
  { 
  var uadd = document.registration.address;
  var letters = /^[0-9a-zA-Z]+$/;
  if(uadd.value.match(letters))
  {
  // Focus goes to next field i.e. Country.
  document.registration.country.focus();
  return true;
  }
  else
  {
  alert('User address must have alphanumeric characters only');
  uadd.focus();
  return false;
  }
  }
  // This function will select country name.
  function countryselect()
  {
  var ucountry = document.registration.country;
  if(ucountry.value == "Default")
  {
  alert('Select your country from the list');
  ucountry.focus();
  return false;
  }
  else
  {
  // Focus goes to next field i.e. ZIP Code.
  document.registration.zip.focus();
  return true;
  }
  }
 // This function will validate ZIP Code.
  function allnumeric()
  { 
  var uzip = document.registration.zip;
  var numbers = /^[0-9]+$/;
  if(uzip.value.match(numbers))
  {
  // Focus goes to next field i.e. email.
  document.registration.email.focus();
  return true;
  }
  else
  {
  alert('ZIP code must have numeric characters only');
  uzip.focus();
  return false;
  }
  }
 // This function will validate Email.
  function ValidateEmail()
  {
  var uemail = document.registration.email;
  var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  if(uemail.value.match(mailformat))
  {
  document.registration.desc.focus();
  return true;
  }
  else
  {
  alert("You have entered an invalid email address!");
  uemail.focus();
  return false;
  }
  }

You can view this Field Level Sample JavaScript Registration From Validation Example in a separate browser window and check how the validation is working.

file_download Download the validation code from here.

Other JavaScript Validation :

Previous: JavaScript Form Validation using a Sample Registration Form
Next: JavaScript: HTML Form - Phone Number validation

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.