Add validation to any form in 2 easy steps:

1. Put “class=” on the fields that you want validated
2. Include this file as validate.js

window.onload = function() {
	prepare();
};
function prepare() {
	regx  = Array();
	// must start with a letter followed by zero or more characters
	regx["startsWithLetter"] = /^[a-z].{0,}$/i;
	regx["digitsOnly"] = /^\d+$/i;

	errMsg = Array();
	errMsg["startsWithLetter"] = "Doesn't start with a letter.";
	errMsg["digitsOnly"] = "Must contain only numbers.";

	var buts = document.getElementsByTagName("input");
	for (var i = 0; i < buts.length; i++) {
		if (buts[i].getAttribute("type") == "submit") {
			buts[i].onclick = function() {
				validate();
				return false;
				};
		}
	}
}
function validateOneField(contents, theClass,  nodeForErrorMessage) {
	var chk = regx[theClass];
	var bText =  chk.test(contents);
	var spans = nodeForErrorMessage.getElementsByTagName("span");
	try {
		for (var k = 0; k < spans.length; k++) {
			if (spans[k].getAttribute("error") == "temp") {
					nodeForErrorMessage.removeChild(spans[k]);
			}
		}
	} catch (e) {}  // not important enough
	if (!bText) {
		var span = document.createElement("span");
		span.setAttribute("error", "temp");
		var nodeText = document.createTextNode(errMsg[theClass]);
		span.appendChild(nodeText);
		nodeForErrorMessage.appendChild(span);
	}
	return bText;
}
function validate() {
	var bReturn = true;
	var inputs = document.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) {
		var type = inputs[i].getAttribute("type");
		if (type != "text") continue;
		var parentNode = inputs[i].parentNode;  // for err msg
		var value = inputs[i].value;  // field contents

		// validate each if it has a class name indicating so
		var className = inputs[i].className;

		if (className) var bValid =
			validateOneField(value, className, parentNode);
		// if it failed, let this whole function fail too
		if (!bValid) bReturn = false;
	}
	return bReturn;
}

And here is some of the HTML

<script type=”text/JavaScript” src=”validate.js”></script>

ID Number:
<input name=”id” type=”text” class=”digitsOnly” />
Name:
<input name=”name” type=”text” class=”startsWithLetter” />

Advertisements

About SunKing2

Former web developer, guitar player, started Piano 2012 -yes still doing it! Recovery, sobriety, mental health advocate.
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s