TextField input length validator : Validation « Form Control « JavaScript DHTML






TextField input length validator

<HTML>
<HEAD>
<TITLE>jaxWidgets by Sarat Pediredla</TITLE>
<STYLE type=text/css>
BODY {
  FONT-SIZE: 0.9em; FONT-FAMILY: Arial, serif
}
A {
  TEXT-DECORATION: none
}
CODE {
  CLEAR: both; DISPLAY: block; FONT-SIZE: 0.9em; FONT-FAMILY: "Courier New", arial, serif; BACKGROUND-COLOR: #00ffcc
}
highlight {
  BACKGROUND-COLOR: #ffff99
}
.header {
  PADDING-RIGHT: 15px; PADDING-LEFT: 10px; FONT-WEIGHT: normal; FONT-SIZE: 2.5em; PADDING-BOTTOM: 15px; MARGIN: 0px; PADDING-TOP: 1px; LETTER-SPACING: -0.05em
}
.header SPAN {
  FONT-SIZE: 0.5em; FONT-FAMILY: Arial, serif; LETTER-SPACING: 0px
}
.toolheader {
  MARGIN: 5px 10px; COLOR: #000000; BORDER-BOTTOM: #69c 2px solid; FONT-FAMILY: arial, serif
}
.layer {
  CLEAR: both; BORDER-RIGHT: #ccc 1px solid; PADDING-RIGHT: 1em; BORDER-TOP: #ccc 1px solid; PADDING-LEFT: 1em; BACKGROUND: #fff; PADDING-BOTTOM: 0.5em; MARGIN: 15px 5%; OVERFLOW: auto; BORDER-LEFT: #ccc 1px solid; PADDING-TOP: 0.5em; BORDER-BOTTOM: #ccc 1px solid
}
.input {
  BORDER-RIGHT: #ff0000 1px solid; BORDER-TOP: #ff0000 1px solid; OVERFLOW: auto; BORDER-LEFT: #ff0000 1px solid; BORDER-BOTTOM: #ff0000 1px solid
}
.button {
  BORDER-RIGHT: #cccccc 1px ridge; PADDING-RIGHT: 2px; BORDER-TOP: #cccccc 1px ridge; PADDING-LEFT: 2px; PADDING-BOTTOM: 2px; BORDER-LEFT: #cccccc 1px ridge; PADDING-TOP: 2px; BORDER-BOTTOM: #cccccc 1px ridge; FONT-FAMILY: serif
}
.note {
  FONT-SIZE: 0.8em
}
detailHeader {
  FONT-WEIGHT: bold
}
detailContent {
  CLEAR: left; DISPLAY: block
}
#mainmenu {
  PADDING-RIGHT: 0.2em; PADDING-LEFT: 0.2em; BACKGROUND: #fff; PADDING-BOTTOM: 0.2em; MARGIN: 0px; PADDING-TOP: 0.2em; BORDER-BOTTOM: #707070 2px solid
}
#mainmenu A {
  BORDER-RIGHT: #fff 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #fff 1px solid; PADDING-LEFT: 5px; FONT-WEIGHT: normal; FONT-SIZE: 16px; PADDING-BOTTOM: 3px; MARGIN: 0px; BORDER-LEFT: #fff 1px solid; COLOR: #333; PADDING-TOP: 3px; BORDER-BOTTOM: #fff 1px solid; TEXT-DECORATION: none
}
#mainmenu A:hover {
  BORDER-RIGHT: #9d9d9d 1px solid; BORDER-TOP: #9d9d9d 1px solid; BACKGROUND: #ccc; BORDER-LEFT: #9d9d9d 1px solid; COLOR: #171717; BORDER-BOTTOM: #9d9d9d 1px solid
}
#mainmenu LI {
  DISPLAY: inline; LINE-HEIGHT: 200%; LIST-STYLE-TYPE: none; TEXT-ALIGN: center
}
.testClass {
  CLEAR: left; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 12px; COLOR: red; FONT-FAMILY: Arial, Helvetica, sans-serif
}

</style>
<!-- <LINK href="progressvalidator_files/jax.css" rel=stylesheet> -->

<!-- jaxWidgets_RuntimeEngine.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.

============= META ==================
@name : jaxWidgets_RuntimeEngine.js  
@version : 0.10 
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 14/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================

============== DESCRIPTION =============
The Runtime Engine to register and process widgets
=========================================

============= FEATURES ==================
- Dynamically loads and parses jaxWidgets
- i18n support for strings
============================================

============= FUTURE PLANS ==================

==============================================

LICENSE: LGPL

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/
// Define namespace
if (typeof jaxWidgets != "object") { var jaxWidgets = {}; }

// Register namespace and object
jaxWidgets.RuntimeEngine = function()
{
  var registeredWidgets = new Array();
  var totalWidgets = -1;
  var loadedWidgets = new Array();
  var currentWidgets = new Array();
  
  this.registerWidget = function(tag, handler)
  {
    var newWidget = new Array(tag, handler);
    registeredWidgets[++totalWidgets] = newWidget;
  };
  
  this.loadEngine = function()
  {
    // Load library component
    _Library = new jaxWidgets.Library();        
    for(var i=0; i <= totalWidgets; i++)
    {
      currentWidgets = document.getElementsByTagName("jax:"+registeredWidgets[i][0]);
      for(var j =0; j < currentWidgets.length; j++)
      {
        registeredWidgets[i][1].load(currentWidgets[j]);
      }
      
      _Library.cleanup(currentWidgets);
    }    
  };
  
  /*
  Debug function for testing purposes only 
  You NEED to create a div with id=debug in your page for this to work
  */
  this.writeDebug = function(string)
  {
    document.getElementById("debug").innerHTML += string + "<br>";
  };
  
  /*
  Error Log function. Can be disabled through setErrors(false)
  */
  this.writeError = function(string)
  {
    if(document.getElementById("jaxErrorLogDiv"))
    {
      document.getElementById("jaxErrorLogDiv").innerHTML += string + "<br>";
    }
    else
    {
      var logDiv = document.createElement("div");
      logDiv.setAttribute("id","jaxErrorLogDiv");
      logDiv.style.color = "red";
      logDiv.style.fontSize = "0.9em";
      logDiv.style.fontWeight = "bold";
      var bodyTag = document.getElementsByTagName("body")[0];
      bodyTag.insertBefore(logDiv,bodyTag.firstChild);
      logDiv.innerHTML = "jax Error : ";
      logDiv.innerHTML += string + "<br>";
    }
  };
      
}

// Register event handlers
// Use quirksmode idea for flexible registration by copying existing events
// onKeyUp
/******* Define GLOBAL Constants *********/
var _Engine;              // The jax Runtime Engine
var _Library;             // The jax Runtime library

_Engine = new jaxWidgets.RuntimeEngine();
var oldEventCode = (window.onload) ? elm.onload : function () {};
window.onload = function () {oldEventCode(); _Engine.loadEngine();};
</SCRIPT>


<!-- jaxWidgets_Library.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.

============= META ==================
@name : jaxWidgets_Library.js  
@version : 0.10 
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 14/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================

============== DESCRIPTION =============
The Library is a repository for common functions used by jaxWidgets
=========================================

============= FEATURES ==================
- Sets Style of elements
============================================

============= CHANGELOG ==================
17 June 2005 [17:46] [Sarat Pediredla]
- Modified code to replace getAttribute().toLowerCase() with tmpString
  because strangely IE 6.0 wont support it.
18 June 2005 [08:45] [Sarat Pediredla]
- Added functions to get X & Y position of elements.
- Modified style setters to use element.style.cssText
==========================================

LICENSE: LGPL

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/

// The following array IS NEEDED for widgets wishing to lock submitting forms
var submitLockedBy = new Array();

// Register object
jaxWidgets.Library = function()
{
  // Cleanup function to remove jax XML tags
  this.cleanup = function(array)
  {
    var arraylength = array.length;
    for(var i=0; i < arraylength; i++)
    {
      var element = array[0];
      element.parentNode.removeChild(element);
    }
    return true;
  }
  
  // Gets the index of an element in an array
  this.getIndex = function(element,array)
  {
    for(var i=0; i < array.length; i++)
    {
      if(array[i] == element)
        return i;
    }
  }
  // Sets the CSS style from source to target element
  this.setStyle = function(sourceElement,targetElement)
  {
    if(sourceElement.getAttribute("style") && sourceElement.getAttribute("style").length > 0)
    {
      targetElement.style.cssText = sourceElement.getAttribute("style");
      return;
    }
    if(sourceElement.getAttribute("class") && sourceElement.getAttribute("class").length > 0)    
    {      
      targetElement.setAttribute("className",sourceElement.getAttribute("class"));
      targetElement.setAttribute("class",sourceElement.getAttribute("class"));
      return;
    }
  }
  
  // Returns parent form of a given element
  this.getParentForm = function(element)
  {
    for(var i=0;i < document.forms.length; i++)
    {
      if(document.forms[i][element.id] == element)
        return document.forms[i];
    }
    _Engine.writeError("jax Error : Your elements are not embedded inside a form");
    return null;
  }
  
  // Returns the submit button for a given form
  this.getSubmitElement = function(currentForm)
  {
    for(i=0;i<currentForm.length;i++)
    {
      var currentElement = currentForm.elements[i];
      var tmpString = currentElement.type;
      if(tmpString.toString().toLowerCase() == "submit")
        return currentElement;
    }
  }
  
  // Disables submitting of forms when fields not validated
  this.disableSubmit = function(element)
  {    
    form = this.getParentForm(element);
    var btnSubmit = this.getSubmitElement(form);    
    if(btnSubmit)
      btnSubmit.disabled = true;
  }
  
  this.enableSubmit = function(element)
  {    
    form = this.getParentForm(element);
    var btnSubmit = this.getSubmitElement(form);
    if(btnSubmit)
      btnSubmit.disabled = false;
  }
  
  this.lockSubmit = function(id)
  {
    var index = _Library.getIndex(id,submitLockedBy)
    if(!(index >= 0))
    {
      submitLockedBy.push(id);    
    }  
    _Library.disableSubmit(document.getElementById(id));
  }
  
  this.unlockSubmit = function(id)
  {
    var index = _Library.getIndex(id, submitLockedBy);
    if(index > -1)
    {
      submitLockedBy.pop(index);
      if(_Library.noSubmitLocks())
        _Library.enableSubmit(document.getElementById(id));
    }
  }
    
  this.noSubmitLocks = function()
  {
    if(submitLockedBy.length <= 0)
      return true;
    return false;
  }
  
  this.getXPos = function(element)
  {
      xPos = element.offsetLeft;
      tempEl = element.offsetParent;
        while (tempEl != null) 
      {
        xPos += (tempEl.offsetLeft);
          tempEl = tempEl.offsetParent;
        }
      return xPos;
  }
  
  this.getYPos = function(element)
  {    
      yPos = element.offsetTop;
      tempEl = element.offsetParent;
        while (tempEl != null) 
      {
        yPos += tempEl.offsetTop;
          tempEl = tempEl.offsetParent;
        }
      return yPos;    
  }
          
}
  
</SCRIPT>

<!-- jaxWidgets_ProgressValidator.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.

============= META ==================
@name : jaxWidgets_ProgressValidator.js  
@version : 0.10 
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 15/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================

============== DESCRIPTION =============
The progress validator widget is a part of the jaxWidgets library. It provides an
interactive progress bar below text fields allowing you to limit characters. 
This is used best in textareas where the progess
=========================================

============= FEATURES ==================
- Uses jaxXML markup tags to specify designer friendly tags in HTML (.NET style)
- i18n support for strings
- Customisable UI
- Use on any number of fields
- Supports both Bar and Text type progress fields.
============================================

============= CHANGELOG ==================
17 June 2005 [17:46]
- Modified code to replace getAttribute().toLowerCase() with tmpString
  because strangely IE 6.0 wont support it.
==========================================

LICENSE: LGPL

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/

jaxWidgets.ProgressValidator = function()
{
  // Validation settings
  maxLength = 20;        // Defines maximum length of field
  minLength = 0;         // Defines minimum length of field
  isRequired = false;    // Is field required?
  
  // i18n settings
  strRequired = "Required";
  strRemaining = "characters remaining";
  strLimit = "Left : ";
  
  // UI settings
  strType = "TEXT";     // Field display type enum{BAR,TEXT}
  BackColor = "#0000FF";
  TextColor = "#FFFFFF";
  BorderColor = "#000000";
  FontSize = "0.7em";
  FontFamily = "Verdana, Arial, serif";
  
  var tmpString;
  
  // Plugin interface to load element
  this.load = function(element)
  {
    if(!element)
    {
      _Engine.writeError('jax Error: Progress Field Validator cannot load');
      return;
    }
        
    var countElement = document.getElementById(element.getAttribute("ControlToValidate"));
    if(!countElement)
    {
      _Engine.writeError('jax Error: Progress validator is missing a ControlToValidate attribute');
      return;
    }    
    
    var progressElement;
    
    // Determine if we need a BAR or TEXT progress displayed
    var tmpType = element.getAttribute("Type");
    if(tmpType == "BAR")
    {
      progressElement = this.createBarProgress(element,countElement);
    }
    else 
    {
      progressElement = this.createTextProgress(element,countElement);
    }

                  
    // Standrad function to parse the custom jax tag
    this.parseTag(element,progressElement);      
    // Create style
    _Library.setStyle(element,progressElement);
    
    tmpString = progressElement.getAttribute("isRequired");
    if(tmpString.toString().toLowerCase() == "true")
    {
      _ProgressValidator.validate(countElement.id);
    }
    
    // Register event handlers
    var oldEventCode = (countElement.onkeyup) ? countElement.onkeyup : function () {};
    countElement.onkeyup = function () {oldEventCode(); _ProgressValidator.validate(countElement.id)};
  }
    
  // Create a text progress layer
  this.createTextProgress = function(element, countElement)
  {
    var progressElement = document.createElement("div");
    progressElement.setAttribute("id",countElement.id+"_prgvalid");
    element.parentNode.insertBefore(progressElement,element.nextSibling);
    return progressElement;
  }
  
  // Create a bar progress layer
  this.createBarProgress = function(element,countElement)
  {    
    var progressElement = document.createElement("div");
    progressElement.setAttribute("id",countElement.id+"_prgvalid");
    progressElement.setAttribute("width","0px");    
    progressElement.setAttribute("maxWidth",countElement.offsetWidth);
    progressElement.style.color = TextColor;
    progressElement.style.backgroundColor = BackColor;
    progressElement.style.overflow = "hidden";
    progressElement.style.height = "15px";    
    progressElement.style.fontSize = FontSize;
    progressElement.style.fontFamily = FontFamily;
    progressElement.style.fontWeight = "bold";
    progressElement.style.display = "block";
    countElement.parentNode.insertBefore(progressElement,countElement.nextSibling);
    return progressElement;
  }
  
  this.validate = function(id)
  {
    var element;
    if(!(element=document.getElementById(id)))
    {
      return false;
    }
    var progressDiv = document.getElementById(id+"_prgvalid");
    switch(progressDiv.getAttribute("strtype"))
    {
      case "BAR" : this.validateBar(element, progressDiv);
             break;
      case "TEXT" : this.validateText(element, progressDiv);
              break;
    }
    return true;
  }
  
  this.parseTag = function(element, progressElement)
  {
    if(element.getAttribute("MaxLength"))
      progressElement.setAttribute("maxLength",element.getAttribute("MaxLength"));
    else
      progressElement.setAttribute("maxLength",maxLength);
      
    if(element.getAttribute("MinLength"))
      progressElement.setAttribute("MinLength",element.getAttribute("MinLength"));
    else
      progressElement.setAttribute("MinLength",minLength);
            
    if(element.getAttribute("Required"))
      progressElement.setAttribute("isRequired",element.getAttribute("Required"));
    else
      progressElement.setAttribute("isRequired",isRequired);
      
    if(element.getAttribute("TextRequired"))
      progressElement.setAttribute("strRequired",element.getAttribute("TextRequired"));
    else
      progressElement.setAttribute("strRequired",strRequired);
      
    if(element.getAttribute("TextRemaining"))
      progressElement.setAttribute("strRemaining",element.getAttribute("TextRemaining"));
    else
      progressElement.setAttribute("strRemaining",strRemaining);
    
    if(element.getAttribute("TextLimit"))
      progressElement.setAttribute("strLimit",element.getAttribute("TextLimit"));
    else
      progressElement.setAttribute("strLimit",strLimit);
      
    if(element.getAttribute("Type"))
      progressElement.setAttribute("strType",element.getAttribute("Type"));
    else
      progressElement.setAttribute("strType",strType);        
      
  }
  
  this.validateText = function(element, progressDiv)
  {        
    // Reset display
    if(progressDiv.getAttribute("isRequired") == "true")
    {
      if(element.value.length <= 0)
      {
        _Library.lockSubmit(element.id);
        progressDiv.innerHTML = progressDiv.getAttribute("strRequired");
        return false;
      }
    }
    if((progressDiv.getAttribute("maxLength") - element.value.length) < 0)
    {
      element.value = element.value.substring(0, progressDiv.getAttribute("maxLength"));      
      return false;
    }      
    progressDiv.innerHTML = "<strong>"+(progressDiv.getAttribute("maxLength") - element.value.length)+"</strong> "+progressDiv.getAttribute("strRemaining");
    _Library.unlockSubmit(element.id);
  }
  
  this.validateBar = function(element, progressDiv)
  {    
    var progressUnit = progressDiv.getAttribute("maxWidth") / progressDiv.getAttribute("maxLength");
    var barSize = element.value.length * progressUnit;
    var progressPercent = parseInt(((progressDiv.getAttribute("maxWidth") - barSize) / progressDiv.getAttribute("maxWidth")) * 100);
    // Reset display
    if(progressDiv.getAttribute("isRequired") == "true")
    {
      if(element.value.length <= 0)
      {
        _Library.lockSubmit(element.id);
        progressDiv.innerHTML = progressDiv.getAttribute("strRequired");
        progressDiv.style.width = progressDiv.getAttribute("maxWidth")+"px";
        return false;
      }
    }
    if((progressDiv.getAttribute("maxLength") - element.value.length) < 0)
    {
      element.value = element.value.substring(0, progressDiv.getAttribute("maxLength"));      
      return false;
    }      
    progressDiv.style.width = barSize+"px";
    progressDiv.innerHTML = progressDiv.getAttribute("strLimit")+progressPercent + "%";
    _Library.unlockSubmit(element.id);
  }
      
  this.registerWithEngine = function(_ProgressValidator)
  {
    var tag = "ProgressValidator";
    var handler = _ProgressValidator;
    _Engine.registerWidget(tag, handler);
  }
}

var _ProgressValidator = new jaxWidgets.ProgressValidator()
_ProgressValidator.registerWithEngine(_ProgressValidator);
      

    
</SCRIPT>

<BODY>
<H2>Demo </H2></DIV>
<DIV class=layer id=jaxDetail>This is a TEXT ProgressValidator <BR><BR>
      <CENTER>
      <FORM id=testForm><INPUT id=test1> <JAX:PROGRESSVALIDATOR MaxLength="10" 
      Required="true" 
      ControlToValidate="test1"></JAX:PROGRESSVALIDATOR><BR></FORM></CENTER>
      
      This is a BAR 
      ProgressValidator <BR><BR>
      <FORM id=testForm2><TEXTAREA id=test2 rows=5 cols=45></TEXTAREA> 
      <JAX:PROGRESSVALIDATOR MaxLength="30" Required="true" 
      ControlToValidate="test2" Type="BAR" 
      TextRequired="Wanted"></JAX:PROGRESSVALIDATOR><BR></FORM>
      <P><STRONG>Code :</STRONG> <BR></BODY></HTML>


           
       








Related examples in the same category

1.Form validation: Not Empty, Valid Radio, is Number, string length, EMail Address
2.Validate an input field with minimum and maximum values
3.Validate an field with a maximum number of characters
4.Phone Number Validation
5.Creating Reusable Validation Code
6.Credit Card Validation
7.Money Format
8.Validating User Input
9.Validate email address
10.Validate a number
11.Password field validator
12.TextField validator: email, IP address and URL
13.Must be at least 3 characters and not more than 8
14.Only characters are allowed
15.Can be empty
16.Must be a valid email address
17.ComboBox(list box): Must be selected one
18.InputBox: value must be between 10 and 90
19.Not stop when the first failed validation is encountered
20.A CSS is used to highlight the fields which failed to validate
21.Need to select a file
22.A simple form with two passwords that must have the same value
23.Shows the usage of callback functions for checking a field
24.Javascript validation framework
25.Form validator library