Simple Javascript validation on form element. It is demo on one element of the form. You need to create simple form like below with one form element and one submit button.
<form method="post" name="user_regform" onSubmit="return check_validity();"> <input type="text" name="fname"/><br> <input type="submit" name="Submit" value="Save" /> </form>
You will call a java script function (check_validity()) on submit of the form. It simply checks client side validation for correct input data.
<script language="javascript" type="text/javascript">
function check_validity()
{
var frm_flag=true;
var msg="";
/* simple if condition for element value check to blank */
if(document.user_regform.fname.value=="")
{
/* if blanck insert msg to msg varible and assign false to flag variable */
msg+="Firstname should not be empty.";
frm_flag=false;
/* input is blank set cursor to input field */
document.user_regform.fname.focus();
}
if(frm_flag==false)
{
/* alert message and return false */
alert(msg);
return false;
}
return true;
}
</script>
You can now validate any element of the form in the similar way. You need to put another validations in “else if” form. It will generate single message at a time.
This validation code was for blank value validation for any element of the form. You can see validation for “character only” or “number only” or “text character and number only” or “correct email format validation” in my next post.
Enjoy it

Leave a Reply