Form Validation in Java

Introduction 

 
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 members of the websites. Forms consist of various fields that nee to be filled in with the candidates, to get all ot the user's details.
 
Sometimes, by mistake, we provide the information in the wrong format. Also, when we provide incomplete information that should be indicated is incorrect, so that the user should be able to modify, or correct the information filled in by the candidates for proper registration.
 
So, by validating the form, it indicates to the user that the information filled in is incorrect (in case of wrong or incorrect information) and makes it correct.
 
Now let's use an example of a form in which we provide various fields and make two files.   One, in JSP for the user interface and the other, in Java form validation the form.
 
We have made these two files individually, one in Java and another in JSP, 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.  <    
  3.  jsp: useBean id = "form"    
  4. class = "validation.Myform"    
  5. scope = "request" >    
  6.  <    
  7.  jsp: setProperty name = "form"    
  8. property = "errorMessages"    
  9. value = '<%= errorMap %>' / >    
  10.  <    
  11.  /jsp:useBean>        
  12.     
  13.  <    
  14.  html >    
  15.  <    
  16.  head >    
  17.  <    
  18.  /head>     <    
  19.  body bgcolor = "green" >    
  20.  <%        
  21.                 
  22.         if ("true".equals(request.getParameter("process"))) {        
  23.     %> <    
  24.  jsp: setProperty name = "form"    
  25. property = "*" / >    
  26.  <%        
  27.                     
  28.             if (form.process())        
  29.         
  30.             {        
  31.         
  32. HttpSession hs=request.getSession();        
  33. hs.setAttribute("name",(String)request.getParameter("name"));        
  34. hs.setAttribute("user",(String)request.getParameter("user"));        
  35. hs.setAttribute("pass",(String)request.getParameter("pass1"));        
  36. hs.setAttribute("address",(String)request.getParameter("address"));        
  37. hs.setAttribute("pin",(String)request.getParameter("pin"));        
  38. hs.setAttribute("contact",(String)request.getParameter("contact"));        
  39. hs.setAttribute("email",(String)request.getParameter("email"));        
  40. hs.setAttribute("city",(String)request.getParameter("city"));        
  41. hs.setAttribute("code",(String)request.getParameter("code"));        
  42. response.sendRedirect("sendmail");        
  43.    }        
  44. }        
  45.         
  46.         
  47.     %>    
  48.     
  49.  <    
  50.  center >    
  51.  <    
  52.  form action = '<%=request.getRequestURI()%>'    
  53. method = "POST" >    
  54.  <    
  55.  table border = "0" >    
  56.  <    
  57.  tbody >    
  58.  <    
  59.  tr >    
  60.  <    
  61.  td > Name < /td>     <    
  62.  td > < input type = "text"    
  63. name = "name"    
  64. value = '<%=form.getName()%>' / > < /td>     <    
  65.  td > < font color = "red" > <%=form.getErrorMessage("name") %> < /font></td >    
  66.  <    
  67.  /tr>     <    
  68.  tr >    
  69.  <    
  70.  td > Username < /td>     <    
  71.  td > < input type = "text"    
  72. name = "user"    
  73. value = '<%=form.getUser()%>' / > < /td>     <    
  74.  td > < font color = "red" > <%=form.getErrorMessage("user") %> < /font></td >    
  75.  <    
  76.  /tr>     <    
  77.  tr >    
  78.  <    
  79.  td > Password < /td>     <    
  80.  td > < input type = "password"    
  81. name = "pass1"    
  82. value = '<%=form.getPass1()%>' / > < /td>     <    
  83.  td > < font color = "red" > <%=form.getErrorMessage("pass1") %> < /font></td >    
  84.  <    
  85.  /tr>     <    
  86.  tr >    
  87.  <    
  88.  td > Re Enter Password < /td>     <    
  89.  td > < input type = "password"    
  90. name = "pass2"    
  91. value = '<%=form.getPass2()%>' / > < /td>     <    
  92.  td > < font color = "red" > <%=form.getErrorMessage("pass2") %> < /font></td >    
  93.  <    
  94.  /tr>     <    
  95.  tr >    
  96.  <    
  97.  td > Address < /td>     <    
  98.  td > < input type = "text"    
  99. name = "address"    
  100. value = '<%=form.getAddress()%>' / > < /td>     <    
  101.  td > < font color = "red" > <%=form.getErrorMessage("address") %> < /font></td >    
  102.  <    
  103.  /tr>     <    
  104.  tr >    
  105.  <    
  106.  td > Pin Number < /td>     <    
  107.  td > < input type = "text"    
  108. name = "pin"    
  109. value = '<%=form.getPin()%>' / > < /td>     <    
  110.  td > < font color = "red" > <%=form.getErrorMessage("pin") %> < /font></td >    
  111.  <    
  112.  /tr>     <    
  113.  tr >    
  114.  <    
  115.  td > Mobile Number < /td>     <    
  116.  td > < input type = "text"    
  117. name = "contact"    
  118. value = '<%=form.getContact()%>' / > < /td>     <    
  119.  td > < font color = "red" > <%=form.getErrorMessage("contact") %> < /font></td >    
  120.  <    
  121.  /tr>     <    
  122.  tr >    
  123.  <    
  124.  td > Email ID < /td>     <    
  125.  td > < input type = "text"    
  126. name = "email"    
  127. value = '<%=form.getEmail()%>' / > < /td>     <    
  128.  td > < font color = "red" > <%=form.getErrorMessage("email") %> < /font></td >    
  129.  <    
  130.  /tr>     <    
  131.  tr >    
  132.  <    
  133.  td > City < /td>     <    
  134.  td > < select name = "area" >    
  135.  <    
  136.  option > Allahabad < /option>     <    
  137.  option > Lucknow < /option>     <    
  138.  option > Varanasi < /option>     <    
  139.  option > Kanpur < /option>     <    
  140.  option > Agra < /option>     <    
  141.  /select></td >    
  142.  <    
  143.  /tr>     <    
  144.  /tbody>     <    
  145.  /table>        
  146.     
  147.  <    
  148.  center > < input type = "submit"    
  149. value = "Register Me" / > < /center>     <    
  150.  input type = "HIDDEN"    
  151. name = "process"    
  152. value = "true" / >    
  153.     
  154.  <    
  155.  /form>     <    
  156.  /center>     <    
  157.  /body>     <    
  158.  /html>        
  159. <%!        
  160.         // Define error messages        
  161.         java.util.Map errorMap = new java.util.HashMap();        
  162.         public void jspInit()        
  163.                          {        
  164.             errorMap.put(Myform.ERR_NAME_BLANK, "PLEASE ENTER YOUR NAME");        
  165.             errorMap.put(Myform.ERR_USER_BLANK, "PLEASE ENTER YOUR USERNAME");        
  166.             errorMap.put(Myform.ERR_USER_LENGTH, "LENGTH SHOULD BE 5 OR MORE");        
  167.             errorMap.put(Myform.ERR_USER_EXISTS, "USERNAME ALREDY EXISTS");        
  168.             errorMap.put(Myform.ERR_PASS1_BLANK, "PLEASE ENTER YOUR PASSWORD");        
  169.             errorMap.put(Myform.ERR_PASS1_LENGTH, "LENGTH SHOULD BE 5 OR MORE");        
  170.             errorMap.put(Myform.ERR_PASS2_BLANK, "PLEASE RE ENTER YOUR PASSWORD");        
  171.             errorMap.put(Myform.ERR_PASS2_MATCH, "PASSWORD DOES NOT MATCH");        
  172.             errorMap.put(Myform.ERR_ADDRESS_BLANK, "PLEASE ENTER YOUR ADDRESS");        
  173.             errorMap.put(Myform.ERR_CONTACT_BLANK, "PLEASE ENTER YOUR MOBILE #");        
  174.             errorMap.put(Myform.ERR_CONTACT_LENGTH, "LENGTH SHOULD BE 10");        
  175.             errorMap.put(Myform.ERR_CONTACT_INVALID, "INVALID CONTACT #");        
  176.             errorMap.put(Myform.ERR_PIN_BLANK, "PLEASE ENTER YOUR PIN CODE");        
  177.             errorMap.put(Myform.ERR_PIN_LENGTH, "LENGTH SHOULD BE 6");        
  178.             errorMap.put(Myform.ERR_PIN_INVALID, "INVALID PIN CODE");        
  179.             errorMap.put(Myform.ERR_EMAIL_BLANK, "PLEASE ENTER YOUR EMAIL ID");        
  180.             errorMap.put(Myform.ERR_EMAIL_INVALID, "INVALID EMAIL ID");        
  181.                          }         
  182.         %>     

The contents are written in <%-------%> is JSP content and apart from these, there is 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 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.    errorCodes.put("name", ERR_NAME_BLANK);  
  129.   }  
  130.   
  131.   if (user.length() == 0) {  
  132.    errorCodes.put("user", ERR_USER_BLANK);  
  133.   } else  
  134.   if (user.length() < 5) {  
  135.    errorCodes.put("user", ERR_USER_LENGTH);  
  136.   } else {  
  137.   
  138.    try {  
  139.     conn ob = new conn();  
  140.     Connection con = ob.c();  
  141.     Statement stm = con.createStatement();  
  142.     ResultSet rst = stm.executeQuery("select * from  client where username='" + user + "'");  
  143.     if (rst.next()) {  
  144.      errorCodes.put("user", ERR_USER_EXISTS);  
  145.     }  
  146.   
  147.    } catch (Exception e) {}  
  148.   
  149.   }  
  150.   if (pass1.length() == 0) {  
  151.    errorCodes.put("pass1", ERR_PASS1_BLANK);  
  152.   } else  
  153.   if (pass1.length() < 5) {  
  154.    errorCodes.put("pass1", ERR_PASS1_LENGTH);  
  155.   }  
  156.   if (pass2.length() == 0) {  
  157.    errorCodes.put("pass2", ERR_PASS2_BLANK);  
  158.   } else  
  159.   if (!(pass1.equals(pass2))) {  
  160.    errorCodes.put("pass2", ERR_PASS2_MATCH);  
  161.   }  
  162.   
  163.   if (address.length() == 0) {  
  164.    errorCodes.put("address", ERR_ADDRESS_BLANK);  
  165.   }  
  166.   
  167.   if (pin.length() == 0) {  
  168.    errorCodes.put("pin", ERR_PIN_BLANK);  
  169.   } else  
  170.   if (pin.length() != 6) {  
  171.    errorCodes.put("pin", ERR_PIN_LENGTH);  
  172.   } else {  
  173.    try {  
  174.     long n1 = Long.parseLong(pin);  
  175.    } catch (NumberFormatException e) {  
  176.     errorCodes.put("pin", ERR_PIN_INVALID);  
  177.    }  
  178.   }  
  179.   
  180.   if (contact.length() == 0) {  
  181.    errorCodes.put("contact", ERR_CONTACT_BLANK);  
  182.   } else  
  183.   if (contact.length() != 10) {  
  184.    errorCodes.put("contact", ERR_CONTACT_LENGTH);  
  185.   } else {  
  186.    try {  
  187.     long n1 = Long.parseLong(contact);  
  188.    } catch (NumberFormatException e) {  
  189.     errorCodes.put("contact", ERR_CONTACT_INVALID);  
  190.    }  
  191.   }  
  192.   if (email.length() == 0) {  
  193.    errorCodes.put("email", ERR_EMAIL_BLANK);  
  194.   } else if (!email.matches(".+@.+\\..+")) {  
  195.    errorCodes.put("email", ERR_EMAIL_INVALID);  
  196.   }  
  197.   
  198.   return errorCodes.size() == 0;  
  199.  }  
  200.   
  201.  public boolean process() {  
  202.   if (!isValid()) {  
  203.    return false;  
  204.   }  
  205.   
  206.   name = "";  
  207.   user = "";  
  208.   pass1 = "";  
  209.   pass2 = "";  
  210.   address = "";  
  211.   contact = "";  
  212.   pin = "";  
  213.   email = "";  
  214.   code = "";  
  215.   
  216.   errorCodes.clear();  
  217.   return true;  
  218.  }  
  219. }   
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.


Similar Articles