Home > DeveloperSection > Beginner > Validation in java script

Validation in java script


JavaScript JavaScript 
Ratings:
0 Comment(s)
 3882  View(s)
Rate this:

Validation in java script

We can use java script to validate user input in html form such as correctness of data. We can use java script to validate required field, email etc. In this demonstration we learn how to validate use input by using java script.

Validating Required Field

Following code snippet create a user form in which we can check required filed validation.

Code:

<body>

    <table border="1" cellpadding="0" cellspacing="0">

        <tr style="visibility:hidden;" id="errorRow">

            <td colspan="2">

                <p id="errorMessage" style="color:Red">

               

                </p>

            </td>

        </tr>

        <tr>

            <td>Login Name</td>

            <td><input type="text" id="txtLoginName" /></td>

        </tr>

        <tr>

            <td>Password</td>

            <td><input type="password" id="txtPassword" /></td>

        </tr>

        <tr>

            <td colspan="2" align="center">

                <input type="button" onclick="btnSubmit()" value="Log In" />

                <input type="reset" style="margin-left:10px;" value="Clear Content" />

            </td>

        </tr>

    </table>

</body>

On click event of button write down following line of code in java script to validate user input

Code:

<script type="text/javascript">

        function btnSubmit() {

            var errArray = "";

            if (document.getElementById("txtLoginName").value.length == 0)

                errArray = "1. Login name field should not be empty.<br />";

            if (document.getElementById("txtPassword").value.length == 0)

                errArray = errArray + "|" + "2. Password field should not be empty.<br />";

            if (errArray.length > 1) {

                document.getElementById("errorMessage").innerHTML = errArray;

                document.getElementById("errorRow").style.visibility = "visible";

            }

            else {

                document.getElementById("errorRow").style.visibility = "collapse";

            }

        }

</script>

Output of the following code snippet is as follows

Validation in java script

Without entering any value in text field if we click on Log In button then following error message is shown….

Validation in java script

After entering value in both fields when we click on Log In button then error messages are invisible.

Validation in java script

 

 

 


Don't want to miss updates? Please click the below button!

Follow MindStick