JavaScript and Field Type Validation

I created a script that checks to see if a field has been populated or not, however, I did not take into effect that the INPUT TYPE could be RADIO, TEXT, or CHECKBOX, as well as a SELECT or TEXTAREA element.

I would like the script to determine the type, then proceed checking to see if the field is populated.

Here is my code so far:

function checkRequiredFields(fieldList) {

// Go through fieldList to see if each field

// is populated/filled in...

var doc = document.forms[0];

var delimiter = "~~";

var i;

var reqField;

var reqFieldDesc;

var reqFieldValue;

var reqFieldType;

var stringToSplit;

var delPos;

var splitFieldList;

splitFieldList = fieldList.split(";");



for (var i = 0; i < splitFieldList.length; i++) {

	stringToSplit = splitFieldList[i];

	delPos = stringToSplit.indexOf(delimiter);

	reqField = stringToSplit.substr(0, delPos);

	reqFieldDesc = stringToSplit.substr(delPos + delimiter.length, stringToSplit.length);

	// Let's check what type of field it is...

	reqFieldType = eval("window.document.forms[0]." + reqField + ".type");		

	reqFieldType = reqFieldType.toUpperCase();

	switch (reqFieldType){

	 	case "TEXT" :

	 		reqFieldValue = eval("window.document.forms[0]." + reqField + ".value");   		

		break;

		

		case "TEXTAREA" :		 	

	

		break;

		

		case "CHECKBOX" :		 	// RADIO type check routine...



	

		break;

		

		case "RADIO" :		                  // RADIO type check routine...

	

		break;

	

		default :

			// Is a multi-value field...

			// check to see if it is empty...				

			reqFieldValue = eval("window.document.forms[0]." + reqField);   		

			// SELECT element check routine...		

	}

	if (reqFieldValue == "") {

		alert("The " + reqFieldDesc + " field is required.  Please enter a value in this field to continue.");  	

		eval("window.document.forms[0]." + reqField + ".focus()");

		return false;	

		break;			

	}

}

return true;

}

Also, does anyone have a quick routine to check if a SELECT element has a selected value and a routine to check if a RADIO or CHECKBOX type has a checked value?

Thanks!

Dan

Subject: JavaScript and Field Type Validation

Just keep in mind that checkboxes and radios may return “undefined”, since they normally appear as several elements on the page with the same name. If you get “undefined”, check the zeroeth element of the array if you need the type. Selects will return -1 for .selectedIndex if nothing’s selected.

Subject: RE: JavaScript and Field Type Validation

Get the element type:reqFieldType = eval(“window.document.forms[0].elements['” + reqField + “']”);

This returns “[object]”. Now, if I reading correctly, if I get the zeroeth element of the [object], that should be the type??? Correct?

Like this?

reqType = reqFieldType[0];

Also, I understand (since I tested it) the “undefined” return value - does that mean the field is unpopulated? If the field is populated, then “undefined” will not be returned, correct?

Thanks!

Dan

Subject: Brute force approach

Don’t forget about the notorious checkbox issue. You can’t send an empty checkbox field to Domino if it previously had items selected.

I have built my own personal method of handling all the various types of web

fields. It’s a brute force approach, but it has worked for me.

Below is my attempt at pasting in a sample script. Send me an email if you

have any questions.

  • Matt

matt_rakestraw@carmax.com

function validateDocument () {

var thisForm = document.forms[0];

var passedValidation = true;



var form = thisForm.Form.value;



var valStr = "";

var wrnStr = "Warnings:\n";

var warn = false;

var errStr = "Cannot save this document because:\n";

var error = false;



//Handle Nullable Checkboxes - Domino workaround



var wclength = thisForm.WorkCat.length;

var wcchecked = false;

for (var z=0; z < wclength; z++) {

	if (thisForm.WorkCat(z).checked) {

		wcchecked = true;

	}

}

thisForm.WorkCatNull.value = ( ( wcchecked ) ? 1 : 0 );



//End of Checkbox handlers





// Normal text field handler



var cstr = thisForm.Subject.value;

if (cstr == "") {

	errStr = errStr + "\tNo Project title or work description 

entered.\n";

	passedValidation = false;

	error = true;

}



// Radio Button handler



var vCstr = thisForm.WorkAsmt;

var tempValid = false;

for (var i=0; i < vCstr.length; i++) {

	if (vCstr[i].checked) {

		tempValid = true;

	}

}

if (!tempValid) {

	errStr = errStr + "\tNo delivery path selected.\n";

	passedValidation = false;

	error = true;

}





// multi-value selection list handler



var listObject = thisForm.BusGroup;

var optionsSelected = new Array;

var j = 0;

for (var i = 0; i < listObject.length; i++) {

	if (listObject.options[i].selected) {

		optionsSelected[j] = listObject.options[i].value;

		j++;

	}

}

if (optionsSelected.length == 0) {

	errStr = errStr + "\tNo Business Group selected.\n";

	passedValidation = false;

	error = true;

}





// single value selection list handler



cstr = thisForm.PELocation.value;

var vCstr = thisForm.PELocation;

var selectedCstr = vCstr.options[vCstr.selectedIndex].text;

if (selectedCstr == "-- Country --") {

	errStr = errStr + "\tNo Country to Perform IT Services was 

selected.\n";

	passedValidation = false;

	error = true;

}



// checking for numbers



cstr = thisForm.RankingTX.value;

if (!(cstr == "")) {

	if (isNaN(cstr)) {

		errStr = errStr + "\tRanking is Not a Number.\n";

		passedValidation = false;

		error = true;

	}else{

		if (cstr<1 | cstr >1000) {

			errStr = errStr + "\tRanking is not in the 

range 1 - 1000.\n";

			passedValidation = false;

			error = true;

		}

	}

}



// Check date field



var cstr = thisForm.StartDate.value;

if (!isDate(cstr)) {

	if (dateErrorReason == "") {

		errStr = errStr + "\tInvalid Start Date.  Please use 

mm/dd/yyyy as your format.\n";

	}else{

		errStr = errStr + "\tInvalid Start Date.  " + 

dateErrorReason + “\n”;

	}

	passedValidation = false;

	error = true;

	dateErrorReason = "";      //dateErrorReason is a global 

variable

}



if (error) valStr = valStr+errStr;

if (warn) valStr = valStr+wrnStr;



if (error || warn) alert(valStr);



return passedValidation;



//return false;   //while debugging the validation code

}

/**

(Javascript/DHTML Tutorials)

*/

// Declaring valid date character, minimum year and maximum year

var dtCh= “/”;

var minYear=1900;

var maxYear=2100;

function isInteger(s){

var i;

	for (i = 0; i < s.length; i++){   

    		// Check that current character is number.

    		var c = s.charAt(i);

    		if (((c < "0") || (c > "9"))) return false;

	}

	// All characters are numbers.

	return true;

}

function stripCharsInBag(s, bag){

var i;

	var returnString = "";



// Search through string's characters one by one.

	// If character is not in bag, append to returnString.

	for (i = 0; i < s.length; i++){   

    		var c = s.charAt(i);

    		if (bag.indexOf(c) == -1) returnString += c;

	}

	return returnString;

}

function daysInFebruary (year){

// February has 29 days in any year evenly divisible by four,

// EXCEPT for centurial years which are not also divisible by 400.

	

return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 

0))) ? 29 : 28 );

}

function DaysArray(n) {

for (var i = 1; i <= n; i++) {

	this[i] = 31;

	if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}

	if (i==2) {this[i] = 29}

} 

return this;

}

function isDate(dtStr){

var daysInMonth = DaysArray(12);

var pos1=dtStr.indexOf(dtCh);

var pos2=dtStr.indexOf(dtCh,pos1+1);

var strMonth=dtStr.substring(0,pos1);

var strDay=dtStr.substring(pos1+1,pos2);

var strYear=dtStr.substring(pos2+1);

strYr=strYear;



if (strDay.charAt(0)=="0" && strDay.length>1) 

strDay=strDay.substring(1);

if (strMonth.charAt(0)=="0" && strMonth.length>1) 

strMonth=strMonth.substring(1);

for (var i = 1; i <= 3; i++) {

	if (strYr.charAt(0)=="0" && strYr.length>1) 

strYr=strYr.substring(1);

}



month=parseInt(strMonth);

day=parseInt(strDay);

year=parseInt(strYr);



if (pos1==-1 || pos2==-1){

	dateErrorReason = "The date format should be : mm/dd/yyyy";

	return false;

}

if (strMonth.length<1 || month<1 || month>12){

	dateErrorReason = "Invalid month";

	return false;

}

if (strDay.length<1 || day<1 || day>31 || (month==2 && 

day>daysInFebruary(year)) || day > daysInMonth[month]){

	dateErrorReason = "Invalid day";

	return false;

}

if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){

	dateErrorReason = "Year must be a valid 4 digit year between 

“+minYear+” and "+maxYear;

	return false;

}

if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, 

dtCh))==false){

	dateErrorReason = "";

	return false;

}

return true;

}

/*

This function (emailCheck) retrieved from the JS-Examples archives

http://www.js-examples.com

1000s of free ready to use scripts, tutorials, forums.

Author: JS-Examples - http://www.js-examples.com/

*/

function emailCheck (emailStr) {

var checkTLD=0; 

var knownDomsPat=/ 

^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

var emailPat=/^(.+)@(.+)$/; 

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]"; 

var validChars="\[^\\s" + specialChars + "\]"; 

var quotedUser="(\"[^\"]*\")"; 

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/; 

var atom=validChars + '+'; 

var word="(" + atom + "|" + quotedUser + ")"; 

var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); 

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$"); 

var matchArray=emailStr.match(emailPat); 



if (matchArray==null) { 

	return false;

	//"The Email Address Is Invalid"; 

}

 

var user=matchArray[1]; 

var domain=matchArray[2]; 



for (i=0; i<user.length; i++) { 

	if (user.charCodeAt(i)>127) { 

		//alert("The Username Contains Invalid Characters."); 

		return false; 

	} 

} 



for (i=0; i<domain.length; i++) { 

	if (domain.charCodeAt(i)>127) { 

		//alert("Ths Domain Name Contains Invalid 

Characters.");

		return false; 

	} 

} 



if (user.match(userPat)==null) { 

	//alert("The Username Is Invalid."); 

	return false; 

} 



var IPArray=domain.match(ipDomainPat); 



if (IPArray!=null) { 

	for (var i=1;i<=4;i++) { 

		if (IPArray>255) { 

			//alert("The Destination IP Address Is 

Invalid.");

			return false; 

		} 

	} 

	return true; 

} 



var atomPat=new RegExp("^" + atom + "$"); 

var domArr=domain.split("."); 

var len=domArr.length; 



for (i=0;i<len;i++) { 

	if (domArr[i].search(atomPat)==-1) { 

		//alert("The Domain Name Is Invalid."); 

		return false; 

	} 

}



if (checkTLD && domArr[domArr.length-1].length!=2 && 

domArr[domArr.length-1].search(knownDomsPat)==-1) { 

	//alert("The Domain Name Extension Is Invalid"); 

	return false; 

} 



if (len<2) { 

	//alert("The Address Is Missing A Hostname."); 

	return false; 

}



return true;

}

Subject: My “Hack” job at it…

Spent some time on this…

Here is my “hack” job…

**doc = document.forms[0];

**fieldName = (field name validating

**elementType = (field type)

“elementType” is determined by using function “getElementType”

I’m sure there is a “cleaner” way of doing this, but it works for me…

function validateField(doc, fieldName, elementType) {

var elementName;

var newObject;

var newObjectValue;

var objectType;

var objectValue;

var radioField;

var checkboxField;

var checkIndex;

var i;

var j;



for (i=0; i < doc.elements.length; i++) {  

	elementName = doc.elements[i].name;

	// Get the correct element based on the fieldName variable...

	if (fieldName == elementName) {   

		// Check to see what .type it is...

		switch (elementType) {

			case "text" :

				objectValue = doc.elements[i].value;

				if (objectValue == "" || objectValue == null) {

					return null;

				}

				else {

					return objectValue;

				}		

			break;

			

			case "radio" :

				radioField = doc.elements[fieldName];

				for (j = 0; j < radioField.length; j++){

					if(radioField[j].checked == true) {						

						objectValue = radioField[j].value;

					}

				}

				if (objectValue == "" || objectValue == null) {

					return null;

				}

				else {

					return objectValue;

				}	

			break;

		

			case "checkbox" :

				checkboxField = doc.elements[fieldName];

				for (j = 0; j < checkboxField.length; j++){

					if (checkboxField[j].checked == true) {

						if (objectValue == "" || objectValue == null) {	

							objectValue = checkboxField[j].value;

						}

						else {

							objectValue = objectValue + ";" + checkboxField[j].value;							

						}								

					}

				}

				if (objectValue == "" || objectValue == null) {

					return null;

				}

				else {

					return objectValue;

				}	

		

			break;

		

			case "select-one" :

				checkIndex = doc.elements[i].selectedIndex;

				if (checkIndex == 0 || checkIndex == -1) {

					return null;

				}

				else {

					objectValue = doc.elements[i].text;

					if (objectValue == "" || objectValue == null) {

						return null;

					}

					else {

						return objectValue;

						

					}	

				}

		

			break;

		

			case "select-multiple" :

				newObject = doc.elements[i];

				checkIndex = doc.elements[i].selectedIndex;

				if(checkIndex == 0 || checkIndex == -1) {

					return null;

				}

				else {

					for (j = 0; j < newObject.options.length; j++) {

						if (newObject.options[j].selected == true) {

							// Check if selected...

							if (objectValue == "" || objectValue == null) {	

								objectValue = newObject.options[j].text;	

							}

							else {							

								objectValue = objectValue + ";" + newObject.options[j].text;		

							}

						}

					}

				}

				if (objectValue == "" || objectValue == null) {

					return null;

				}

				else {

					return objectValue;

				}	



			break;

		

			case "textarea" :

				objectValue = doc.elements[i].value;

				if(objectValue=="" || objectValue==null) {

					return null;

				}

				else {

					return objectValue;

				}		

			break;

		

			case "file" :

		

			break;

			

			case "button" :

		

			break;

			

			case "password" :

		

			break;

			

			case "reset" :

		

			break;

			

			case "submit" :

		

			break;

		

			default :

		}

	}

}

return null;

}

function getElementType(doc, fieldName) {

 for(var i=0; i < doc.elements.length; i++) {  

	var elementName = doc.elements[i].name;

	if (fieldName == elementName) {   

		return doc.elements[i].type; 

	}        

}

return null;

}

HTH… someone…

Dan