Form Validation in Java

This article explains how to validate the form using Java with complete explanations.

Form validation

Whenever we go through web sites, we need to register ourselves to become the members of the websites. Forms consist of various fields to be filled in with the candidates to get all the details of the user.

But sometimes by mistake we provide the information in the wrong format or incomplete information that should be indicated is incorrect so that user should be able to modify or correct the information filled in by the candidates for proper registration.

So by validating the form, in other words to indicate to the user that the information filled in is incorrect (in case of wrong or incorrect information) and make it correct.

Now let's use an example of a form in which we provide various fields and we make two files, one in JSP for the user interface and another in Java form validation the form.

We have made these two files individually, one in Java and another in JSP, but within one project so that the two can be connected to each other for proper validation.

Form.jsp

  1. <%@page import="validation.Myform" contentType="text/html" pageEncoding="UTF-8"%>  
  2. <jsp:useBean id="form" class="validation.Myform" scope="request">  
  3.         <jsp:setProperty name="form" property="errorMessages" value='<%= errorMap %>'/>  
  4. </jsp:useBean>  
  5.   
  6. <html>  
  7.     <head>  
  8. </head>  
  9. <body bgcolor="green">  
  10.     <%  
  11.           
  12.         if ("true".equals(request.getParameter("process"))) {  
  13.     %>  
  14.             <jsp:setProperty name="form" property="*" />  
  15.     <%  
  16.               
  17.             if (form.process())  
  18.   
  19.             {  
  20.   
  21. HttpSession hs=request.getSession();  
  22. hs.setAttribute("name",(String)request.getParameter("name"));  
  23. hs.setAttribute("user",(String)request.getParameter("user"));  
  24. hs.setAttribute("pass",(String)request.getParameter("pass1"));  
  25. hs.setAttribute("address",(String)request.getParameter("address"));  
  26. hs.setAttribute("pin",(String)request.getParameter("pin"));  
  27. hs.setAttribute("contact",(String)request.getParameter("contact"));  
  28. hs.setAttribute("email",(String)request.getParameter("email"));  
  29. hs.setAttribute("city",(String)request.getParameter("city"));  
  30. hs.setAttribute("code",(String)request.getParameter("code"));  
  31. response.sendRedirect("sendmail");  
  32.    }  
  33. }  
  34.   
  35.   
  36.     %>    
  37.       
  38.                <center>  
  39.                   <form action='<%=request.getRequestURI()%>' method="POST">  
  40.                       <table border="0">  
  41.                               <tbody>  
  42.                               <tr>  
  43.                                   <td>Name</td>  
  44.                                   <td><input type="text" name="name" value='<%=form.getName()%>'/></td>  
  45.                                   <td><font color="red"><%=form.getErrorMessage("name") %></font></td>  
  46.                               </tr>  
  47.                               <tr>  
  48.                                   <td>Username</td>  
  49.                                   <td><input type="text" name="user" value='<%=form.getUser()%>'/></td>  
  50.                                   <td><font color="red"><%=form.getErrorMessage("user") %></font></td>  
  51.                               </tr>  
  52.                               <tr>  
  53.                                   <td>Password</td>  
  54.                                   <td><input type="password" name="pass1" value='<%=form.getPass1()%>' /></td>  
  55.                                   <td><font color="red"><%=form.getErrorMessage("pass1") %></font></td>  
  56.                               </tr>  
  57.                               <tr>  
  58.                                   <td>Re Enter Password</td>  
  59.                                   <td><input type="password" name="pass2" value='<%=form.getPass2()%>' /></td>  
  60.                                   <td><font color="red"><%=form.getErrorMessage("pass2") %></font></td>  
  61.                               </tr>  
  62.                               <tr>  
  63.                                   <td>Address</td>  
  64.                                   <td><input type="text" name="address" value='<%=form.getAddress()%>' /></td>  
  65.                                   <td><font color="red"><%=form.getErrorMessage("address") %></font></td>  
  66.                               </tr>  
  67.                               <tr>  
  68.                                   <td>Pin Number</td>  
  69.                                   <td><input type="text" name="pin" value='<%=form.getPin()%>' /></td>  
  70.                                   <td><font color="red"><%=form.getErrorMessage("pin") %></font></td>  
  71.                               </tr>  
  72.                               <tr>  
  73.                                   <td>Mobile Number</td>  
  74.                                   <td><input type="text" name="contact" value='<%=form.getContact()%>' /></td>  
  75.                                   <td><font color="red"><%=form.getErrorMessage("contact") %></font></td>  
  76.                               </tr>  
  77.                               <tr>  
  78.                                   <td>Email ID</td>  
  79.                                   <td><input type="text" name="email" value='<%=form.getEmail()%>'/></td>  
  80.                                   <td><font color="red"><%=form.getErrorMessage("email") %></font></td>  
  81.                               </tr>  
  82.                               <tr>  
  83.                                   <td>City</td>  
  84.                                   <td><select name="area">  
  85.                                           <option>Allahabad</option>  
  86.                                           <option>Lucknow</option>  
  87.                                           <option>Varanasi</option>  
  88.                                           <option>Kanpur</option>  
  89.                                           <option>Agra</option>  
  90.                                       </select></td>  
  91.                               </tr>  
  92.                           </tbody>  
  93.                       </table>  
  94.   
  95.                               <center><input type="submit" value="Register Me" /></center>  
  96.                       <input type="HIDDEN" name="process" value="true"/>  
  97.   
  98.                   </form>  
  99.               </center>  
  100. </body>  
  101. </html>  
  102. <%!  
  103.         // Define error messages  
  104.         java.util.Map errorMap = new java.util.HashMap();  
  105.         public void jspInit()  
  106.                          {  
  107.             errorMap.put(Myform.ERR_NAME_BLANK, "PLEASE ENTER YOUR NAME");  
  108.             errorMap.put(Myform.ERR_USER_BLANK, "PLEASE ENTER YOUR USERNAME");  
  109.             errorMap.put(Myform.ERR_USER_LENGTH, "LENGTH SHOULD BE 5 OR MORE");  
  110.             errorMap.put(Myform.ERR_USER_EXISTS, "USERNAME ALREDY EXISTS");  
  111.             errorMap.put(Myform.ERR_PASS1_BLANK, "PLEASE ENTER YOUR PASSWORD");  
  112.             errorMap.put(Myform.ERR_PASS1_LENGTH, "LENGTH SHOULD BE 5 OR MORE");  
  113.             errorMap.put(Myform.ERR_PASS2_BLANK, "PLEASE RE ENTER YOUR PASSWORD");  
  114.             errorMap.put(Myform.ERR_PASS2_MATCH, "PASSWORD DOES NOT MATCH");  
  115.             errorMap.put(Myform.ERR_ADDRESS_BLANK, "PLEASE ENTER YOUR ADDRESS");  
  116.             errorMap.put(Myform.ERR_CONTACT_BLANK, "PLEASE ENTER YOUR MOBILE #");  
  117.             errorMap.put(Myform.ERR_CONTACT_LENGTH, "LENGTH SHOULD BE 10");  
  118.             errorMap.put(Myform.ERR_CONTACT_INVALID, "INVALID CONTACT #");  
  119.             errorMap.put(Myform.ERR_PIN_BLANK, "PLEASE ENTER YOUR PIN CODE");  
  120.             errorMap.put(Myform.ERR_PIN_LENGTH, "LENGTH SHOULD BE 6");  
  121.             errorMap.put(Myform.ERR_PIN_INVALID, "INVALID PIN CODE");  
  122.             errorMap.put(Myform.ERR_EMAIL_BLANK, "PLEASE ENTER YOUR EMAIL ID");  
  123.             errorMap.put(Myform.ERR_EMAIL_INVALID, "INVALID EMAIL ID");  
  124.                          }   
  125.         %> 

The contents written in <%-------%> is JSP content and apart from these there are HTML content that we are all familiar with.

Output:

Form validation in Java


You can see in the output that there are many fields like name, username, password and so on that are to be filled in by the candidates.

Now the Java file to validate the form.

We need to make the various packages for this file and we have also included the package in the Java file along with some mandatory packages.

Myform.java

  1. package validation;  
  2. import java.sql.*;  
  3. import java.util.*;  
  4. import database.conn;  
  5.   
  6.   
  7.   
  8. public class Myform {  
  9.   
  10. String name="";  
  11. String user="";  
  12. String pass1="";  
  13. String pass2="";  
  14. String address="";  
  15. String contact="";  
  16. String pin="";  
  17. String email="";  
  18. String code="";  
  19.   
  20.     public String getName() {  
  21.         return name;  
  22.     }  
  23.   
  24.     public void setName(String name) {  
  25.         this.name = name;  
  26.     }  
  27.   
  28.     public String getUser() {  
  29.         return user;  
  30.     }  
  31.   
  32.     public void setUser(String user) {  
  33.         this.user = user;  
  34.     }  
  35.   
  36.     public String getPass1() {  
  37.         return pass1;  
  38.     }  
  39.   
  40.     public void setPass1(String pass1) {  
  41.         this.pass1 = pass1;  
  42.     }  
  43.   
  44.     public String getPass2() {  
  45.         return pass2;  
  46.     }  
  47.   
  48.     public void setPass2(String pass2) {  
  49.         this.pass2 = pass2;  
  50.     }  
  51.   
  52.     public String getAddress() {  
  53.         return address;  
  54.     }  
  55.   
  56.     public void setAddress(String address) {  
  57.         this.address = address;  
  58.     }  
  59.   
  60.     public String getContact() {  
  61.         return contact;  
  62.     }  
  63.   
  64.     public void setContact(String contact) {  
  65.         this.contact = contact;  
  66.     }  
  67.   
  68.     public String getPin() {  
  69.         return pin;  
  70.     }  
  71.   
  72.     public void setPin(String pin) {  
  73.         this.pin = pin;  
  74.     }  
  75.   
  76.     public String getEmail() {  
  77.         return email;  
  78.     }  
  79.   
  80.     public void setEmail(String email) {  
  81.         this.email = email;  
  82.     }  
  83.   
  84.     public static final Integer ERR_NAME_BLANK = new Integer(1);  
  85.     public static final Integer ERR_USER_BLANK = new Integer(2);  
  86.     public static final Integer ERR_USER_LENGTH = new Integer(3);  
  87.     public static final Integer ERR_USER_EXISTS = new Integer(4);  
  88.     public static final Integer ERR_PASS1_BLANK = new Integer(5);  
  89.     public static final Integer ERR_PASS1_LENGTH = new Integer(6);  
  90.     public static final Integer ERR_PASS1_INVALID = new Integer(17);  
  91.     public static final Integer ERR_PASS2_BLANK = new Integer(7);  
  92.     public static final Integer ERR_PASS2_MATCH = new Integer(8);  
  93.     public static final Integer ERR_ADDRESS_BLANK = new Integer(9);  
  94.     public static final Integer ERR_PIN_BLANK = new Integer(10);  
  95.     public static final Integer ERR_PIN_LENGTH = new Integer(11);  
  96.     public static final Integer ERR_PIN_INVALID = new Integer(12);  
  97.     public static final Integer ERR_CONTACT_BLANK = new Integer(13);  
  98.     public static final Integer ERR_CONTACT_LENGTH = new Integer(14);  
  99.     public static final Integer ERR_CONTACT_INVALID = new Integer(15);  
  100.     public static final Integer ERR_EMAIL_BLANK = new Integer(16);  
  101.     public static final Integer ERR_EMAIL_INVALID = new Integer(17);  
  102.   
  103.   
  104.     Map errorCodes = new HashMap();  
  105.   
  106.     Map msgMap;  
  107.     public void setErrorMessages(Map msgMap) {  
  108.         this.msgMap = msgMap;  
  109.     }  
  110.   
  111.     public String getErrorMessage(String propName) {  
  112.         Integer code = (Integer) (errorCodes.get(propName));  
  113.         if (code == null) {  
  114.             return "";  
  115.         } else if (msgMap != null) {  
  116.             String msg = (String) msgMap.get(code);  
  117.             if (msg != null) {  
  118.                 return msg;  
  119.             }  
  120.         }  
  121.         return "Error";  
  122.     }  
  123.     public boolean isValid() {  
  124.   
  125.         errorCodes.clear();  
  126.   
  127.    if(name.length()==0)  
  128.    {  
  129.    errorCodes.put("name", ERR_NAME_BLANK);  
  130.    }  
  131.   
  132.    if(user.length()==0)  
  133.    {  
  134.    errorCodes.put("user",ERR_USER_BLANK);  
  135.    }  
  136.    else  
  137.        if(user.length()<5)  
  138.        {  
  139.        errorCodes.put("user",ERR_USER_LENGTH);  
  140.        }  
  141.    else  
  142.        {  
  143.   
  144.        try  
  145.        {  
  146.        conn  ob=new conn();  
  147.        Connection con=ob.c();  
  148.        Statement stm=con.createStatement();  
  149.        ResultSet rst=stm.executeQuery("select * from  client where username='"+user+"'");  
  150.        if(rst.next())  
  151.        {  
  152.        errorCodes.put("user",ERR_USER_EXISTS);  
  153.        }  
  154.   
  155.        }  
  156.        catch(Exception e)  
  157.        {}  
  158.   
  159.        }  
  160.         if(pass1.length()==0)  
  161.    {  
  162.    errorCodes.put("pass1",ERR_PASS1_BLANK);  
  163.    }  
  164.    else  
  165.        if(pass1.length()<5)  
  166.        {  
  167.        errorCodes.put("pass1",ERR_PASS1_LENGTH);  
  168.        }  
  169.    if(pass2.length()==0)  
  170.    {  
  171.    errorCodes.put("pass2",ERR_PASS2_BLANK);  
  172.    }  
  173.    else  
  174.        if(!(pass1.equals(pass2)))  
  175.        {  
  176.        errorCodes.put("pass2",ERR_PASS2_MATCH);  
  177.        }  
  178.   
  179.    if(address.length()==0)  
  180.    {  
  181.    errorCodes.put("address", ERR_ADDRESS_BLANK);  
  182.    }  
  183.   
  184.    if(pin.length()==0)  
  185.    {  
  186.    errorCodes.put("pin",ERR_PIN_BLANK);  
  187.    }  
  188.    else  
  189.        if(pin.length()!=6)  
  190.        {  
  191.        errorCodes.put("pin",ERR_PIN_LENGTH);  
  192.        }  
  193.    else  
  194.        {  
  195.        try  
  196.        {  
  197.        long n1=Long.parseLong(pin);  
  198.        }  
  199.        catch(NumberFormatException e)  
  200.        {  
  201.        errorCodes.put("pin",ERR_PIN_INVALID);  
  202.        }  
  203.        }  
  204.   
  205.    if(contact.length()==0)  
  206.    {  
  207.    errorCodes.put("contact",ERR_CONTACT_BLANK);  
  208.    }  
  209.    else  
  210.        if(contact.length()!=10)  
  211.        {  
  212.        errorCodes.put("contact",ERR_CONTACT_LENGTH);  
  213.        }  
  214.    else  
  215.        {  
  216.        try  
  217.        {  
  218.        long n1=Long.parseLong(contact);  
  219.        }  
  220.        catch(NumberFormatException e)  
  221.        {  
  222.        errorCodes.put("contact",ERR_CONTACT_INVALID);  
  223.        }  
  224.        }  
  225.         if (email.length() == 0) {  
  226.             errorCodes.put("email", ERR_EMAIL_BLANK);  
  227.         } else if (!email.matches(".+@.+\\..+")) {  
  228.             errorCodes.put("email", ERR_EMAIL_INVALID);  
  229.         }  
  230.   
  231.    return errorCodes.size() == 0;  
  232.     }  
  233.   
  234.     public boolean process() {  
  235.         if (!isValid()) {  
  236.             return false;  
  237.         }  
  238.         
  239. name="";  
  240. user="";  
  241. pass1="";  
  242. pass2="";  
  243. address="";  
  244. contact="";  
  245. pin="";  
  246. email="";  
  247. code="";  
  248.   
  249.        errorCodes.clear();  
  250.         return true;  
  251. }  

In the code above we can see the validation packages are included along with one package of a database is also included so that all the details of the user are saved in the database if the user has filled in all the fields correctly.

For this we have made various types of errors that may be done by the user. Like this we can also make more types of errors depending on our needs.

Output

The output after filling in some fields incorrectly is as follows:

Form validation in Java1

In the output we can see the errors in red due to the incorrect information filled in by the candidate. The errors “length username should be 5 or more”, “mobile number should be of 10 digits” and “invalid email” are shown because the user did not write ”@”. Since we have specified the errors, the errors are shown using validation that is done here in Java.

Up Next
    Ebook Download
    View all
    Learn
    View all