Saturday 6 April 2013

Simple form validations using JavaScript

In this article I will show you how to perform simple JavaScript validations to a form submit.

Below is the working model.


 

Source Code:

Try to use the below code in any HTML editor.
<html>
<head>
    <script>
        function formvalidate() {
            if (document.getElementById("txtName").value == "") {
                alert("Enter Name");
            }
            else if (document.getElementById("txtPassword").value == "") {
                alert("Enter Password");
            }
            else if (document.getElementById("rbtmale").checked == false && document.getElementById("rbtfemale").checked == false) {
                alert("Select Gender");
            }
            else if (document.getElementById("ddlLocation").value == 0) {
                alert("Select Location");
            }
            else if (document.getElementById("ftpImage").value == "") {
                alert("Upload file");
            }
            else {
                alert("Submited");
            }
        }
    </script>
</head>
<body>
    <div style="border-radius: 10px; border: 5px solid green; padding: 20px; width: 280px;">
        <table cellpadding="5" cellspacing="5">
            <tr>
                <td><label> Name </label></td>
                <td><input id="txtName" type="text" /></td>
            </tr>
            <tr>
                <td><label> Password </label></td>
                <td><input id="txtPassword" type="password" /></td>
            </tr>
            <tr>
                <td><label> Gender</label></td>
                <td>
                    <input id="rbtmale" type="radio" />
                    <label> Male </label>
                    <input id="rbtfemale" type="radio" />
                    <label>Female</label>
                </td>
            </tr>
            <tr>
                <td><label> Location </label></td>
                <td>
                    <select id="ddlLocation">
                        <option value="0">Select Location</option>
                        <option value="1">Banglore</option>
                        <option value="2">Chennai</option>
                        <option value="3">Delhi</option>
                        <option value="4">Hyderabad</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td><label> Upload </label></td>
                <td><input id="ftpImage" type="file" /></td>
            </tr>
            <tr>
                <td><input onclick="formvalidate()" type="button" value="Submit" /></td>
            </tr>
        </table>
    </div>
</body>
</html>

No comments:

Post a Comment