javascript based form validation

In this example, we write javascript code to validate the input entries of a form.

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

    <script language="javascript" type="text/javascript">
        function validate()
        {
            var name = document.getElementById("txtname");
            var passwd = document.getElementById("txtpasswd");
            var cpasswd = document.getElementById("txtcpasswd");

            if (name.value.length == 0)
            {
                alert("Name cannot be blank");
                name.focus();
                return false;
            }

            if (name.value.length < 3 || name.value.length > 8)
            {
                alert("Name must be in range");
                name.focus();
                return false;
            }

            if (passwd.value.length == 0)
            {
                alert("password must be entered");
                passwd.focus();
                return false;
            }

            if (passwd.value != cpasswd.value)
            {
                alert("passwords must match");
                passwd.focus();
                return false;
            }

            return true;
        }
    
    </script>
</head>
<body>
<form id="frm" name="frm" method="post" action=""
      onsubmit="return validate();">
    <table>
        <tr>
            <td>Name</td><td><input id="txtname" 
                name="txtname" type="text" maxlength="10" /></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><input id="txtpasswd"
       name="txtpasswd" type="password" /></td>
        </tr>
        <tr>
            <td>Confirm Password</td>
            <td><input id="txtcpasswd"
       name="txtcpasswd" type="password" /></td>
        </tr>
        <tr>
            <td></td>
            <td><input id="btnsubmit" name="btnsubmit"
              type="submit" value="Submit" /></td>
        </tr>

    </table>
</form>

</body>
</html>

 

Add a Comment

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