jQuery form validation example


In this tutorials, we going to use jQuery to validate the form on the client machine. jQuery is the most popular JavaScript Library. It has many predefined methods that make the scripting much simpler.

How to use jQuery

You have two option to integrate jQuery in your project.

  1. By downloading the library. Download
  2. By using CDN. Check CDN

JS Snippet

To get the values of forms input, we have val() method. Its return the value of input form specified by id attribute

 function formValidationFn() {
                // geting the values of form input
                var userName = $("#uname").val();
                var userEmail = $("#uemail").val();
                var userPass = $("#upass").val();

                // checking the condition
                if (userName === null || userName === "") {
                    alert("Name can't be blank.");
                    return false;
                } else if (userEmail === null || userEmail === "") {
                    alert("Email can't be blank.");
                    return false;
                } else if (userPass === null || userPass === "") {
                    alert("Password can't be blank.");
                    return false;
                } else {
                    return true;
                }
            }

Check the full example

<!DOCTYPE html>
<html>
    <head>
        <title>jQuery Form Validation Example</title>
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
        <script type="text/javascript">
            function formValidationFn() {
                // geting the values of form input
                var userName = $("#uname").val();
                var userEmail = $("#uemail").val();
                var userPass = $("#upass").val();

                // checking the condition
                if (userName === null || userName === "") {
                    alert("Name can't be blank.");
                    return false;
                } else if (userEmail === null || userEmail === "") {
                    alert("Email can't be blank.");
                    return false;
                } else if (userPass === null || userPass === "") {
                    alert("Password can't be blank.");
                    return false;
                } else {
                    return true;
                }
            }
        </script>
    </head>
    <body>
        <form action="welcome.jsp" method="GET" onsubmit="return formValidationFn();">
            <pre>		
		Name: <input type="text" id="uname" />	
	
		Email: <input type="text" id="uemail" />
		
		Password: <input type="password" id="upass" />
		
		<input type="submit" value="Login" />
            </pre>
        </form>
    </body>
</html>

Similar Posts

About the Author

Websparrow
I like sharing my experiments and ideas with everyone by writing articles on the latest technological trends.