javascript validating required fields

One way to perform check on all the required input fields is by assigning a class name in the “class” property, and check all those fields whose “class” property is set with value “required”. The following example demonstrates that.

<!DOCTYPE html>
<html>
<head>
    <title>Untitled document</title>
  <meta charset="utf-8" />
    <style>
        .required
        {

        }
    </style>
    <script language="javascript" type="text/javascript">
    function validate()
    {
        var formElements = document.getElementById("frm").elements;
        var status = true;
        for (var i = 0; i < formElements.length; i++)
        {
            if (formElements[i].className == "required") {
                if (formElements[i].value.length == 0) {
                    status = false;
                }
            }
        }

        return status;
    }
    </script>
</head>
<body>
<form id="frm" name="frm" method="post" action="" onsubmit="return validate();">
<table border="1">
    <tr>
        <td>Enter Name</td>
        <td><input id="txtname" name="txtname" 
              type="text" class="required" /></td>
    </tr>

    <tr>
        <td>Password</td>
        <td><input id="txtname" name="txtname" 
              type="password" class="required" /></td>
    </tr>

    <tr>
        <td>Hobbies</td>
        <td>
            <input id="txthobby" name="txthobby"
                   type="text"/>
        </td>
    </tr>

    <tr>
        <td></td>
        <td><input id="btn" name="btn" type="submit" /></td>
    </tr>


</table>    
</form>

</body>
</html>

 

 

Add a Comment

Your email address will not be published. Required fields are marked *