Monday, 29 February 2016

JavaScript Validation for Simple Login Page

Create the DynaminWeb project in Eclipse and paste the below login.jsp and help.jsp into webcontet folder then create the js folder and paste the login.js

========================================================
login.jsp
========================================================

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="js/login.js"></script>

</head>
<body><center>
<div class="container">
<div class="main">
<h2>Login Form</h2>
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" name="username" id="username"/><br>
<label>Password :</label>
<input type="password" name="password" id="password"/><br>
<input type="button" value="Login" id="submit" onclick="validate()"/>
<a href="help.jsp" title="Help"><span class="question">Help</span></a>
</form>

<!--<span><b class="note">Note : </b>use following username and password. <br/><b class="valid">User Name : suresh<br/>Password :pass</b></span>
--></div>
</div></center>
</body>
</html>

==========================================================
login.js
==========================================================
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ( username == "suresh" && password == "pass"){
alert ("Login successfully");
window.location = "help.jsp"; // Redirecting to other page.
return false;
}
else{
attempt --;// Decrementing by one.
alert("You have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}

==========================================================
help.jsp
==========================================================
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<span><b class="note">Note : </b>For this demo use following username and password. <br/><b class="valid">User Name : suresh<br/>Password : pass</b></span>
<a href="index.jsp">Go to Back</a>
</body>
</html>

No comments:

Post a Comment