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>

