TextField validator: email, IP address and URL
<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>
<!-- 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_Validator.js -->
<SCRIPT language=javascript type="text/javascript">
/*
* This notice must be untouched at all times.
============= META ==================
@name : jaxWidgets_Validator.js
@version : 0.10
@copyright (c) 2005 Sarat Pediredla. All rights reserved.
@last-modified: 27/06/2005
@url : http://sarat.xcelens.co.uk/jaxWidgets
@latest-version-url : http://sarat.xcelens.co.uk/jaxWidgets/latest/
======================================
============== DESCRIPTION =============
The validator widget is a part of the jaxWidgets library. It provides
dynamic in-page validation of common fields.
=========================================
============= 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
- Validates most common formats
============================================
============= CHANGELOG ==================
==========================================
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
*/
// Register object
jaxWidgets.Validator = function()
{
// Validation settings
var isRequired = "false";
// Common regexs
var regexEmail = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/;
var regexUrl = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([\w]+)(.[\w]+){1,2}$/;
var regexDate = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
var regexTime = /^([1-9]|1[0-2]):[0-5]\d$/;
var regexIP = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var regexInteger = /(^-?\d\d*$)/;
// United states specific regexs
var regexPostcode_US = /\d{5}(-\d{4})?/;
var regexSSN_US = /\d{3}-\d{2}-\d{4}/;
var regexPhone_US = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;
var regexState_US = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i;
// United Kingdom specific regexs
var regexPostcode_UK = /^([A-Za-z]{1,2})([0-9]{2,3})([A-Za-z]{2})$/;
// i18n settings
var strLocale = "US";
var strType = "String";
var strRequired = "Required";
var strInvalid = "Invalid format";
// Internal global vars
var tmpString;
// Create validator
this.load = function(element)
{
if(!element)
{
_Engine.writeError('jax Error: Validator cannot load');
return;
}
var fieldElement = document.getElementById(element.getAttribute("ControlToValidate"));
if(!fieldElement)
{
_Engine.writeError('jax Error: Validator is missing a ControlToValidate attribute');
return;
}
// Create validator layer
var validatorElement = document.createElement("span");
validatorElement.setAttribute("id",fieldElement.id+"_valid");
element.parentNode.insertBefore(validatorElement,element.nextSibling);
// Standard function to parse the custom jax tag
this.parseTag(element,validatorElement);
// Create style for current element using DOM compatible function from Library
_Library.setStyle(element, validatorElement);
tmpString = validatorElement.getAttribute("isRequired")
if(tmpString.toString().toLowerCase() == "true")
{
_Validator.validate(fieldElement.id);
}
// Register event handlers
// Use quirksmode idea for flexible registration by copying existing events
// onSubmit
var parentForm = _Library.getParentForm(fieldElement);
var oldEventCode = (parentForm.onsubmit) ? parentForm.onsubmit : function () {};
parentForm.onsubmit = function () {oldEventCode(); return _Validator.validate(fieldElement.id)};
// onBlue
var oldEventCode = (fieldElement.onblur) ? fieldElement.onblur : function () {};
fieldElement.onblur = function () {oldEventCode(); return _Validator.validate(fieldElement.id)};
};
this.setInvalid = function(div)
{
div.innerHTML = div.getAttribute("strInvalid");
};
this.validate = function(id)
{
var element;
if(!(element = document.getElementById(id)))
{
return false;
}
var validDiv = document.getElementById(id+"_valid");
var validString = element.value;
if(validString.length == 0)
{
tmpString = validDiv.getAttribute("isRequired");
var isRequired = tmpString.toString().toLowerCase();
if(isRequired == "true")
{
validDiv.innerHTML = validDiv.getAttribute("strRequired");
return false;
}
else
{
validDiv.innerHTML = "";
}
}
// If we have reached here, we can continue with validation
var tmpLocale = validDiv.getAttribute("strLocale");
switch(validDiv.getAttribute("strType"))
{
case "String" :
return true;
break;
case "Email" :
if(!validString.match(regexEmail))
{ this.setInvalid(validDiv); return false; }
break;
case "Url" :
if(!validString.match(regexUrl))
{ this.setInvalid(validDiv); return false; }
break;
case "Date" :
if(!validString.match(regexDate))
{ this.setInvalid(validDiv); return false; }
break;
case "Time" :
if(!validString.match(regexTime))
{ this.setInvalid(validDiv); return false; }
break;
case "IP" :
if(!validString.match(regexIP))
{ this.setInvalid(validDiv); return false; }
break;
case "Integer" :
if(!validString.match(regexInteger))
{ this.setInvalid(validDiv); return false; }
break;
case "Postcode" :
switch(tmpLocale)
{
case "US" :
if(!validString.match(regexPostcode_US))
{ this.setInvalid(validDiv); return false; }
break;
case "Email" :
if(!validString.match(regexPostcode_UK))
{ this.setInvalid(validDiv); return false; }
break;
}
break;
// No need to check locale for SSN as it is US specific
case "SSN" :
if(!validString.match(regexSSN_US))
{ this.setInvalid(validDiv); return false; }
break;
case "Phone" :
switch(tmpLocale)
{
case "US" :
if(!validString.match(regexPhone_US))
{ this.setInvalid(validDiv); return false; }
break;
}
break;
// Only US States work for now
case "State" :
switch(tmpLocale)
{
case "Email" :
if(!validString.match(regexState_US))
{ this.setInvalid(validDiv); return false; }
break;
}
break;
// Do custom validation
case "Custom" :
if(!validString.match(validDiv.getAttribute("Match")))
{ this.setInvalid(validDiv); return false; }
break;
}
// If we have reached here, everything is OK
validDiv.innerHTML = "";
return true;
};
/********* Custom tag parser **********/
this.parseTag = function(element,validatorElement)
{
if(element.getAttribute("Required"))
validatorElement.setAttribute("isRequired",element.getAttribute("Required"));
else
validatorElement.setAttribute("isRequired",isRequired);
if(element.getAttribute("TextRequired"))
validatorElement.setAttribute("strRequired",element.getAttribute("TextRequired"));
else
validatorElement.setAttribute("strRequired",strRequired);
if(element.getAttribute("TextInvalid"))
validatorElement.setAttribute("strInvalid",element.getAttribute("TextInvalid"));
else
validatorElement.setAttribute("strInvalid",strInvalid);
if(element.getAttribute("Type"))
validatorElement.setAttribute("strType", element.getAttribute("Type"));
else
validatorElement.setAttribute("strType", strType);
if(element.getAttribute("Locale"))
validatorElement.setAttribute("strLocale", element.getAttribute("Locale"));
else
validatorElement.setAttribute("strLocale", strLocale);
if(element.getAttribute("Match"))
validatorElement.setAttribute("strCustom", element.getAttribute("Match"));1
};
this.registerWithEngine = function(_Validator)
{
var tag = "Validator";
var handler = _Validator;
_Engine.registerWidget(tag, handler);
};
}
var _Validator = new jaxWidgets.Validator();
_Validator.registerWithEngine(_Validator);
</SCRIPT>
<BODY>
<H2>Demo</H2>
<DIV class=layer id=jaxDetail>This is a demo for jax Validators <BR><BR>
<FORM id=testForm name=form method=post>IP Address :
<INPUT id=ip>
<JAX:VALIDATOR class=testClass Required="true" Type="IP" ControlToValidate="ip">
</JAX:VALIDATOR>
<BR>Email:
<INPUT id=email>
<JAX:VALIDATOR class=testClass Required="true" Type="Email" ControlToValidate="email" TextRequired="Cant be empty">
</JAX:VALIDATOR>
<BR>URL :
<INPUT id=url>
<JAX:VALIDATOR class=testClass Type="Url" ControlToValidate="url" TextInvalid="Need website">
</JAX:VALIDATOR>
<BR>
<INPUT id=submitbtn type=submit value=submit>
</FORM>
</BODY>
</HTML>
Related examples in the same category