If number of form fields are unknown or there are many form in your application and you want to validate all of them in a generic way using less code then you can use logic given below.
HTML Form Code:
<form method="POST" action="loginform.html" onSubmit="return validateLoginForm(this);"> <tr><td width="25%" align="right">User Name:</td> <td align="left"><input id="username" type="text" name="username" value="" size="35"/></td></tr><br> <tr><td width="25%" align="right">Password:</td> <td align="left"><input id="password" type="password" name="password" value="" size="35"/></td></tr><br> <tr> <td colspan=2 align="center"><input type="submit" value="Submit" /></td> </tr> </form>
Javascript Code:
function validateLoginForm(formObj){ for (var i=0; i<formObj.elements.length; i++) { var element = formObj.elements[i]; var trimmedvalue = element.value.trim(); if (trimmedvalue.length == 0 && element.type != 'submit'){ alert("Please supply a User ID & Password."); return false; } } }