Wednesday, January 26, 2011

Form Validation in JSP

What is Validation ?
Validation refers the process of validating/checking out of data that is about to handled by your program. In this process we validate the type of data , size of data and format of data. if it is found wrong or unacceptable we display an appropriate message to user so that he can re-enter his data in real way so that program can work successfully. The main goal of validation is to make the program prevent any bug that causes by user mistake.
How does we Validate data ?
In the early age of programming this task can be only done by the code developed by programmers itself  but now a days , advance technologies provide a sophisticated way to validate our data.
Example of Validation in JSP Program ?
Here I am giving a piece of code to validate the two integer against null. In this program if a user miss to enter any one of data the program guides him to enter the value.
Run the program by paste the code in index page. Hope this will give to a bit signal to understand validation.
Never miss to put your comment if like this topic.
index.jsp
<%
String elder = request.getParameter("age1");
String younger = request.getParameter("age2");
boolean first = false;
int totalage = 0;
String message = "";
if (elder == null) {
first = true;
message = "Your results will appear here";
} else {
try {
int fred = Integer.parseInt(elder);
int doris = Integer.parseInt(younger);
totalage = fred + doris;
} catch (Exception e) {
message = "You must enter two Integers";
first = true;
}
}
// -------------------------------------------------------
%>
<html>
<head><title>Example for first JSP Practical</title></head>
<body><h1>JSP is like a Jumbo Jet Driver</h1>
Because the smallest of operators can do a mighty lot<hr>
<% if (! first) { %>
Inputs were <%= elder %> and <%= younger %><br>
The total age of the kids is <%= totalage %>
<% } else { %>
<%= message %>
<% } %>
<hr>
<form>Please enter age 1 <input name=age1> and
age 2 <input name=age2> and <input type=submit></form>
Copyright ....
</body>
</html>