Daniel Rench

Web application development : Servers : Networks : E-Mail : DNS : Databases : Programming for hire

previous : contact : linkedin : code : links : pictures : facebook : twitter : next

Element.getAttribute() doesn't get enough publicity

For years I've been using hacks like overloading the title and class attributes of HTML elements because I didn't know any better. Now I know I can just make up attributes, like 'regex' here, which I defined as a pattern that a form field must match:

<html>
<head><title>attributes</title>
<script>

function make_validator (form) {

	return function () {
		var pat, r;

		for (var i=0, e; e = form[i]; ++i) {

			pat = e.getAttribute('regex');
			if (! pat) continue;

			r = RegExp(pat).exec(e.value);
			if (! r) {
				e.focus();
				alert("Bad value for " + e.name);
				return false;
			}
		}
		return true;
	};
}

window.onload = function () {

	for (var i=0, form; form=document.forms[i]; ++i)
		form.onsubmit = make_validator(form);

};

</script>
</head>

<body>
<form>
	Number: <input type="text" name="number" regex="^\d+$">
	<input type="submit">
</form>

<form>
	Username: <input type="text" name="username" regex="^\w{1,8}$">
	<input type="submit">
</form>

</body>
</html>

<< We are all bigots / So filled with hatred / We release our poisons | Home | Portfolio | Contact | It might help somebody: Flash 9 with Firefox on a Mac >>