In Your Eyes

Simple HTML Form Validation

February 23, 2008 · 4 Comments

I have a simple javascript code to perform simple HTML form validation. This validation can only check whether the elements, that types are textbox, textarea and password in the form is empty or not.

Just follow the naming standard for each error label id.
For example:

<span style="visibility:hidden;" id="frm_simple_lblError0" class="Error">*</span>

The id attribute in the code above means:

  • frm_simple is the id of the HTML form which will be validated.
  • lblError0 is the error label id for the first textbox or textarea or password in the form.

In summary, frm_simple_lblError0 means an error label id for first textbox or textarea or password in the form with frm_simple as id.

Dont forget to add this code on the onsubmit event inside the form declaration.
For example:

<form name="frm_simple" onsubmit="return checkForm(frm_simple)" method="POST">

Of course you can customize (using others naming standard) or even enhance the code.

This is the complete code.

Filename: main.js
function checkForm(frmId)
{
var elements=frmId.elements;
var isValid=true;
var j=0;
for(var i=0;i<elements.length;i++)
{
if(elements[i].type=="text" || elements[i].type=="password" || elements[i].type=="textarea")
{
errId=frmId.name+"_lblError"+j;
errDivId=document.getElementById(errId);
if(elements[i].value=="")
{
errDivId.style.visibility='visible';
isValid=false;
}
else
{
errDivId.style.visibility='hidden';
}
j++;
}
}
if(isValid)
{
alert("Form Oke!");
}
return isValid;
}

Filename: simple_form.html
<html>
<head>
<title>Simple Form Validation</title>
</head>
<style type="text/css">
*
{
font-family:verdana;
font-size:8pt;
}
.Error
{
color:red;
}
</style>
<script type="text/javascript" src="main.js">
</script>
<body>
<form name="frm_simple" onsubmit="return checkForm(frm_simple)" id="frm_simple" method="POST">
<table border="0">
<tr>
<td style="width:180px">Label 1</td>
<td>:</td>
<td>
<input type="text" name="txt_1" id="txt_1" />
<span id="frm_simple_lblError0" style="visibility:hidden" class="Error">*</span>
</td>
</tr>
<tr>
<td valign="top">Label 2</td>
<td valign="top">:</td>
<td>
<textarea name="txt_2" id="txt_2" cols="30" rows="5"></textarea>
<span id="frm_simple_lblError1" style="visibility:hidden" class="Error">*</span>
</td>
</tr>
<tr>
<td colspan="3" align="right">
<input type="submit" name="btn_save" value="Proses" />
<input type="reset" name="btn_cancel" value="Hapus" />
</td>
</td>
</tr>
</table>
</form>
</body>
</html>

Happy coding!

Categories: Code

4 responses so far ↓

Leave a Comment