Skip to content

Instantly share code, notes, and snippets.

@chernomyrdin
Created December 2, 2011 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chernomyrdin/1422820 to your computer and use it in GitHub Desktop.
Save chernomyrdin/1422820 to your computer and use it in GitHub Desktop.
js form
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
body {
background-color: white;
}
form .field .red {
display: none;
color: red;
}
form .field .error .red {
display: block;
}
</style>
<script type="text/javascript">
function clearError (e) {
if (e) {
e.className = "";
}
return true;
}
function setError (e,m) {
if (e) {
e.className = "error";
if (m) {
var reds = e.getElementsByClassName("red");
if (reds && reds.length) {
reds[0].innerHTML = m;
}
}
}
return false;
}
function checkField (i) {
var rc = true;
if (i.name) {
switch (i.name) {
case "i1":
if (!i.value.match(/^[a-z]*$/)) {
rc = setError(i.parentNode, "Only lower-case alpha");
}
break;
case "i2":
if (!i.value.match(/^[0-9]*$/)) {
rc = setError(i.parentNode, "Only digits");
}
break;
}
if (rc) {
clearError(i.parentNode);
}
}
return false;
}
function checkForm (f) {
var rc = true;
for (var i = 0, max_i = f.elements.length; i < max_i; i++) {
rc = (checkField(f.elements[i]) && rc);
}
return false;
}
</script>
</head>
<body>
<form name="theForm" onsubmit="return(checkForm(this))">
<fieldset>
<div class="field">
<div class="">
<label for="input-1">Input #1</label>
<input type="text" id="input-1" name="i1" onblur="return(checkField(this))" />
<div class="red"></div>
</div>
</div>
<div class="field">
<div class="">
<label for="input-2">Input #2</label>
<input type="text" id="input-2" name="i2" onblur="return(checkField(this))" />
<div class="red"></div>
</div>
</div>
</fieldset>
<input type="submit" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment