File: /home/investoo.co.uk/public_html/js/validate.js
/*Script to validate a form automatically. (c) Steve. Howie.
The script is controlled by an attribute added to the element's tag. e.g.
First Name: <INPUT TYPE="text" ID="firstname" validate="R#alpha##" />
which means "firstname is Required and must be alpha only".
Password: <INPUT TYPE="text" ID="password" validate="R#length#6#8" />
which means "password is Required and must be 6 to 8 chars long".
The validate attribute has four parts separated by the # symbol.
i.e validate="part1#part2#part3#part4"
Part 1 = R for required N for not required.
Part 2 = The type of validation. The possible validation types are:
"email" - no other part required e.g. validate="N#email##"
"alpha" - no other part required, but include extra characters in part3 e.g. validate="N#alpha#'-#"
"numeric" - no other part required, but include extra characters in part3 e.g. validate="N#numeric#,.#"
"alphanumeric" - no other part required, but include extra characters in part3 e.g. validate="N#alphanumeric##"
"range" - lowest and highest number required e.g. validate="N#range#2.6#9.8"
"length" - minimum and maximum length required e.g. validate="N#length#6#8"
"date" - check date format. Part 1 is format and part 2 is seperator / or -. Both required.
Valid formats: dd/mm/yyyy, dd-mm-yyyy, mm/dd/yyyy, mm-dd-yyyy, yyyy-mm-dd, yyyy/mm/dd
e.g "N#date#dd/mm/yyyy#/" or "N#date#yyyy-mm-dd#-"
Parts 3 and 4 = Used for extra values required for the validation type (see length and range above)
Examples:
validate="R#alpha##" - Required field containing only the alphabet. Smith is valid, but O'Donnell is not (need to add ' to the extra chars)
validate="N#numeric#$,.#" - Not required field containing numbers and the additional characters $,. $2,000.00 is valid, but �2,000 is not
validate="N#range#0#140" - Not a required, but number must be in range 0 to 140 inclusive. 45 is valid 200 is not
validate="R#T#length#6#10 - Required field of length 6 to 10 chars inclusive. password is valid, but pass is not (too few letters)
validate="R#date#dd/mm/yyyy#/" - Required date in EU 4 year date format with a slash / seperator.
The form tag needs to call formValidator as follows;
<form method="POST" action="some.php" onsubmit="return formValidator(this);"> */
var oldstyle=new Array(); //An array to store the old border style for after we have highlighted with a red border the errors.
function checkRequired(elem, required) //Check reuired elements filled in
{
required = required.toUpperCase()
if(required=='R' && elem.value.length==0)
{
elem.style.border="2px solid #ff0000";
return 1;
}
return 0;
}
function escapeSpecial(someString)
{ //Make sure some special chars are escaped properly to prevent errors
someString=someString.replace(/\\/g,'\\');
someString=someString.replace(/,/g,'\\,');
someString=someString.replace(/-/g,'\\-');
someString=someString.replace(/\$/g,'\\$');
someString=someString.replace(/\[/g,'\\[');
someString=someString.replace(/\]/g,'\\]');
someString=someString.replace(/\./g,'\\.');
return someString;
}
function isNumeric(elem, extrachars){ //Check numbers only
var numExp = new RegExp("^[0-9" + escapeSpecial(extrachars) +"]+$");
if(elem.value.match(numExp)){
return true;
}
else if(elem.value.length>0)
{
elem.style.border="2px solid #ff0000";
if(extrachars.length>0) {extrachars = " and\n the characters: " + extrachars;}
alert("Error:\nPlease ensure the highlighted field\ncontains numbers" + extrachars);
elem.focus();
return false;
}
}
function isAlpha(elem, extrachars){ //Check alphabet only
var alphaExp = new RegExp("^[a-zA-Z" + escapeSpecial(extrachars) +"]+$");
if(elem.value.match(alphaExp)){
return true;
}
else if(elem.value.length>0)
{
elem.style.border="2px solid #ff0000";
if(extrachars.length>0) {extrachars = " and\n the characters: " + extrachars;}
alert("Error:\nPlease ensure the highlighted field\ncontains only alphabetic letters" + extrachars);
elem.focus();
return false;
}
}
function isAlphanumeric(elem, extrachars){ //Check only alphanumeric
var alphaExp = new RegExp("^[0-9a-zA-Z" + escapeSpecial(extrachars) +"]+$");
if(elem.value.match(alphaExp)){
return true;
}
else if(elem.value.length>0)
{
elem.style.border="2px solid #ff0000";
if(extrachars.length>0) {extrachars = " and\n the characters: " + extrachars;}
alert("Error:\nPlease ensure the highlighted field\ncontains only letters and numbers" + extrachars);
elem.focus();
return false;
}
}
function isRange(elem, low, high){ //Check the min and max length of the string
var uInput = Number(elem.value);
if(uInput >= low && uInput <= high){
return true;
}
else if(elem.value.length>0)
{
elem.style.border="2px solid #ff0000";
alert("Error:\nPlease enter a number between " + low + " and " + high + " in\n the highlighted field.");
elem.focus();
return false;
}
}
function isLength(elem, min, max){ //Check the min and max length of the string
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}
else if(elem.value.length>0)
{
elem.style.border="2px solid #ff0000";
alert("Error:\nPlease enter between " +min+ " and " +max+ " characters in\n the highlighted field.");
elem.focus();
return false;
}
}
function madeSelection(elem){
if(elem.value == "Please Choose"){
elem.style.border="2px solid #ff0000";
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
function isEmail(elem){ //Check the email is valid
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}
else if(elem.value.length>0)
{
elem.style.border="2px solid #ff0000";
alert("Error:\nThe e-mail entered is not valid.\n\nPlease check and try again.");
elem.focus();
return false;
}
else
{
return true;
}
}
function isDate(elem, dateFormat, dateSeparator)
{ //Check the date is valid
var dateStr = elem.value;
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
if (dateFormat == "yyyy-mm-dd" || dateFormat == "yyyy/mm/dd") { datePat = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;}
var matchArray = dateStr.match(datePat); // is the format ok?
var datestatus=true;
datemsg="";
if (matchArray == null || matchArray[1]==null)
{
datemsg="Error:\nPlease enter date as " + dateFormat + "\n";
alert(datemsg);
return false;
}
if(matchArray[3]==null || matchArray[5]==null)
{
datemsg="Error:\nPlease enter date as " + dateFormat + "\n";
alert(datemsg);
return false;
}
if(matchArray[2]!=dateSeparator || matchArray[4]!=dateSeparator)
{
datemsg="Error:\nPlease enter date as " + dateFormat + "\n" + "with a '" + dateSeparator + "' to separate values\n";
alert(datemsg);
return false;
}
if (dateFormat == "mm/dd/yyyy" || dateFormat == "mm-dd-yyyy")
{
month = matchArray[1]; // parse date into variables for USA date
day = matchArray[3];
year = matchArray[5];
}
else if (dateFormat == "dd/mm/yyyy" || dateFormat == "dd-mm-yyyy")
{
month = matchArray[3]; // parse date into variables for EU dates
day = matchArray[1];
year = matchArray[5];
}
else
{
month = matchArray[3]; // parse date into variables for yyyy-mm-dd format
day = matchArray[5];
year = matchArray[1];
}
if (month < 1 || month > 12)
{ // check month range
datemsg=datemsg + "- Month must be between 1 and 12." + "\n";
datestatus=false;
}
if (day < 1 || day > 31)
{ //check day range
datemsg=datemsg + "- Day must be between 1 and 31." + "\n";
datestatus=false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31)
{ //Check months with 30 days
datemsg=datemsg + "- Month " + month + " doesn`t have 31 days!" + "\n";
datestatus=false;
}
if (month == 2)
{ // check for february 29th and leap year
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day > 29 || (day==29 && !isleap))
{
datemsg=datemsg + "- February " + year + " doesn`t have " + day + " days!" + "\n";
datestatus=false;
}
}
if (datemsg != "") //Output message as an alert if there is one.
{
datemsg = "Error:\n" + datemsg;
elem.style.border="2px solid #ff0000";
alert(datemsg);
elem.focus();
}
return datestatus;
}
function restoreStyle(elem, eIndex) //Function to store then restore styles after they have been changed to highlight errors.
{
var eStyles;
if(oldstyle.length < (eIndex+1)) //Style hasn't been stored. So store it!
{
oldstyle[eIndex] = elem.style.borderTop + "!"; //Use an ! as a seperator so we can split them out later
oldstyle[eIndex] += elem.style.borderBottom + "!";
oldstyle[eIndex] += elem.style.borderLeft + "!";
oldstyle[eIndex] += elem.style.borderRight;
}
if((elem.style.borderTopWidth=="2px") && (elem.style.borderTopColor=="#ff0000" || elem.style.borderTopColor=="rgb(255, 0, 0)") && (navigator.appName!="Microsoft Internet Explorer")) //restore old style if the current style is red. Doesn't work in IE
{
eStyles=oldstyle[eIndex].split("!"); //Split out the styles for use
elem.style.borderTop = eStyles[0];
elem.style.borderBottom = eStyles[1];
elem.style.borderLeft = eStyles[2];
elem.style.borderRight = eStyles[3];
}
if((elem.style.borderTopWidth=="2px") && (elem.style.borderTopColor=="#ff0000") && (navigator.appName=="Microsoft Internet Explorer"))
{
//Internet explorer does not correctly re-assign the style in the case of a blanked style attribute so change to green for OK!
elem.style.border = "1px solid #00ff00";
}
}
function formValidator(theform)
{
var numElements=theform.length;
var eIndex, fElement, valParts, requiredNum=0;
var returnVal=false;
//Enumerate form elements and check required elements are filled in and display message if not
for(eIndex=0; eIndex < numElements ; eIndex++)
{
fElement=theform.elements[eIndex];
if(fElement.getAttribute('validate')!=null)
{
valParts=fElement.getAttribute('validate').split('#');
restoreStyle(fElement, eIndex); //restore the style attribute
requiredNum += checkRequired(fElement, valParts[0]); //Calculate number of fields not filled in
}
}
if(requiredNum!=0)
{
alert("Error:\n" + requiredNum + " required fields need to be completed.\n\nRequired fields have been highlighted in red.");
return false;
}
//Check the data is correct
for(eIndex=0; eIndex < numElements ; eIndex++)
{
fElement=theform.elements[eIndex];
if(fElement.getAttribute('validate')!=null)
{
valParts=fElement.getAttribute('validate').split('#');
valParts[1]=valParts[1].toLowerCase();
switch(valParts[1])
{
case 'email':
if(isEmail(fElement)==false)
{ return false; }
break;
case 'alpha':
if(isAlpha(fElement, valParts[2])==false)
{ return false; }
break;
case 'numeric':
if(isNumeric(fElement, valParts[2])==false)
{ return false; }
break;
case 'alphanumeric':
if(isAlphanumeric(fElement, valParts[2])==false)
{ return false; }
break;
case 'range':
if(isRange(fElement, Number(valParts[2]), Number(valParts[3]))==false)
{ return false; }
break;
case 'length':
if(isLength(fElement, valParts[2], valParts[3])==false)
{ return false; }
break;
case 'date':
if(isDate(fElement, valParts[2], valParts[3])==false)
{ return false; }
break;
}
}
}
return true;
}
function deleteCheck(userName)
{
return confirm('About to delete user "' + userName + '" from\nthe list of users.\n\nClick [OK] to confirm.');
}
/* Function to show or hide a div or other element or table row on a click.
example: <a href="#" onclick="showhide('archived')>
and the item to hide: <div id="archived" style="display: none;">
*/
function showhide(id){
if (document.getElementById){ // DOM3 = IE5, NS6
obj = document.getElementById(id);
if (obj.style.display == "none")
{
obj.style.display = "";
}
else
{
obj.style.display = "none";
}
}
else
{
if (document.layers) // NS 4
{
if(document.id.display=="none")
{
document.id.display ="";
}
else
{
document.id.display = "none";
}
}
else
{ // IE 4
if(document.all.id.style.display=="none")
{
document.all.id.style.display ="";
}
else
{
document.all.id.style.display = "none";
}
}
}
}
/* Function to hide all elements of a given type with a given id.
Give elements you want to hide the same first four letters in the id,
e.g. id='faqs001' and id='faqs002' then call elemHide('tr','faqs');
*/
function elemHide(tag, idleft)
{
var numElements=document.getElementsByTagName(tag).length;
var eIndex, fElement;
//Enumerate form elements and check required elements are filled in and display message if not
for(eIndex=0; eIndex < numElements ; eIndex++)
{
fElement=document.getElementsByTagName(tag)[eIndex];
if(fElement.id.substring(0,4)==idleft)
{
if (document.getElementById)
{ // DOM3 = IE5, NS6
document.getElementById(fElement.id).style.display = "none";
}
}
}
}
function imageToggle(img, onoff)
{ /*Function to swap an image based upon a mouse-over event. Image must have two versions name.gif and nameOver.gif
Call example: onmouseover="imageToggle(this,'on');" onmouseout="imageToggle(this,'off');" */
var myRegExp;
if (document.images)
{
if (onoff=="on")
{
myRegExp=/.gif/;
img.src = img.src.replace(myRegExp,"Over.gif");
} else {
myRegExp=/Over.gif/;
img.src = img.src.replace(myRegExp,".gif");
}
}
}
//Function to locate the page width etc
function pageWidth()
{
return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?
document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}
function pageHeight()
{
return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?
document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}
function posLeft()
{
return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ?
document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}
function posTop()
{
return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ?
document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}
function posRight() {return posLeft()+pageWidth();}
function posBottom() {return posTop()+pageHeight();}
/* Function to open a window centered on the screen plus a few other bits */
function windowOpener(wlocation, wtitle, wproperties)
{
//Set default values
wlocation = typeof(wlocation) != 'undefined' ? wlocation : '';
if(wlocation=='') return;
wtitle = typeof(wtitle) != 'undefined' ? wtitle : '';
wproperties = typeof(wtitle) != 'undefined' ? wproperties : '';
var fileType=wlocation.substr(-4,4);
var screenWidth=pageWidth();
var screenHeight=pageHeight();
var theWindow, width, height, top, left;
//Open a special window for images
if(wlocation.indexOf(".jpg") || wlocation.indexOf(".gif") || wlocation.indexOf(".png"))
{
wlocation="/pages/imageShow.php?image=" + escape(wlocation);
}
theWindow = window.open(wlocation, wtitle, wproperties);
//Have height and width been passed? If so use. Otherwise calculate 2/3 width and 3/4 height
if(wproperties.indexOf("width")>-1){
if(theWindow.outerWidth>0) { //FF
width=theWindow.outerWidth;
} else {
width=theWindow.document.body.clientWidth+20; //IE
}
} else {
width=Math.round(screenWidth/3)*2;
}
if(wproperties.indexOf("height")>-1){
if(theWindow.outerHeight>0) {
height=theWindow.outerHeight;
} else {
height=theWindow.document.body.clientHeight+50;
}
} else {
height=Math.round(screenHeight/4)*3;
}
left=Math.round((screenWidth-width)/2);
top=Math.round((screenHeight-height)/2);
theWindow.resizeTo(width,height);
theWindow.moveTo(left, top);
theWindow.focus();
}