Wednesday, July 16, 2008

jQuery Attribute-Based Form Validation Example

Ok, this code is rough, and I'm sure this has been done before, but while playing around with jQuery I thought it might be interesting to try out some form validation by just adding an additional attribute to the input type, then having jQuery search through all the form elements, and then based on that added attribute, test the form values for correctness. Below is a really crude example that demos this technique. It works, I'm not sure if some xhtml validators will squak because of the extra attribute. Anyway, something to play with. One jQuery plugin, one error object (not in this demo) with an array of error strings, and wallah!, form validation. This example will get you thinking.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<title>Untitled Page</title>
<script src="jquery-1.2.6.pack.js" type="text/javascript"></script>
<style type="text/css">
.red {border-color:Red;background-color:Yellow}
</style>
</
head>
<
body>
<
form name="myform">
<
table>
<tr>
<td>Required Numeric1</td>
<td>
<input type="text" id="num1" name="NumericField" v="RN" maxlength="3" />
</td>
</tr>
<tr>
<td>Required Numeric2</td>
<td>
<input type="text" id="num2" name="NumericField2" v="RN" maxlength="3" />
</td>
</tr>
<tr>
<td>Required Numeric3</td>
<td>
<input type="text" id="num3" name="NumericField3" v="RN" maxlength="3" />
</td>
</tr>
<tr>
<td>Numeric4</td>
<td>
<input type="text" id="num4" name="NumericField4" v="N" maxlength="10" />
</td>
</tr>
</
table>
<
input type="button" value="Validate" onclick="return vF('myform');" />
</
form>
<
script language="javascript" type="text/javascript">
var bR = false;
$(document).ready(
function() {
bR=
true;
});
function vF(f)
{
try
{
var sErr = "";
var fid = "";
if(bR==false)return;
$(
"form").find("input[@v='RN']").each(
function()
{
if (isNaN(this.value) this.value=="")
{
sErr+=
"* Required numeric value for " + this.name + ".\n";
this.value = "";
fid = (fid ==
"" ? this.id : fid);
$(
"#"+this.id).addClass("red");
}
else {$("#"+this.id).removeClass("red");}
});
$(
"form").find("input[@v='N']").each(
function()
{
if (isNaN(this.value))
{
sErr+=
"* Numeric value required for " + this.name + ".\n";
this.value = "";
fid = (fid ==
"" ? this.id : fid);
$(
"#"+this.id).addClass("red");
}
else {$("#"+this.id).removeClass("red");}
});
if(sErr != "")
{
sErr =
"Please Correct the following issues-\n" + sErr;
alert(sErr);
$(
"#" + fid).focus();
return false;
}
return true;
}
catch(err)
{
alert(err);
}
}
</script>
</
body>
</
html>

No comments: