How to validate input fields in Java web application

In this Java web application development tutorial, Let’s see how can we prepare a proper framework. Before start database transactions or Servlet request, we must need to validate the user data.

How to validate input fields in Java

Let’s create a custom class (DataValidator.java).¬†This class will be responsible to validate all the data that will come from the inputs fields So we are going to write some methods that will help us to validate the input fields in java.

Validate text field

public static boolean isName(String val) {

  String name = "^[A-Za-z ]*$";
  if (val.matches(name)) {
    return true;
  } else {
    return false;
  }
}

Validate password input field

public static boolean isPassword(String val) {
  String passregex = "^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\\S])[A-Za-z0-9\\S]{6,12}$";

  if (val.matches(passregex)) {
    return true;
  } else {
    return false;
  }
}

Validate phone number input field

public static boolean isPhoneNo(String val) {
  String regex = "^[7-9][0-9]{9}$";
  if (val.matches(regex)) {
    return true;
  } else {
    return false;
  }
}

Validate Date input field

public static boolean isDate(String val) {

  Date d = null;
  if (isNotNull(val)) {
    d = DataUtility.getDate(val);
  }
  return d != null;
}

Validate null or not null input field

public static boolean isNull(String val) {
    if (val == null || val.trim().length() == 0) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * Checks if value is NOT Null
   * 
   * @param val
   * @return
   */
  public static boolean isNotNull(String val) {
    return !isNull(val);
  }

Validate Email field

public static boolean isEmail(String val) {

  String emailreg = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
  if (isNotNull(val)) {
    try {
      return val.matches(emailreg);
    } catch (NumberFormatException e) {
      return false;
    }

  } else {
    return false;
  }
}

Validate Integer value

public static boolean isInteger(String val) {

    if (isNotNull(val)) {
      try {
        int i = Integer.parseInt(val);
        return true;
      } catch (NumberFormatException e) {
        return false;
      }

    } else {
      return false;
    }
  }

Validate long value

public static boolean isLong(String val) {
  if (isNotNull(val)) {
    try {
      long i = Long.parseLong(val);
      return true;
    } catch (NumberFormatException e) {
      return false;
    }

  } else {
    return false;
  }
}

We can add more validation methods its depend on the requirement. In this java web application development tutorial, We are going to create a college project so it enough as per my requirements.

Data Validator Class

package com.javawebapp.utility;

import java.text.ParseException;
import java.util.Date;

/**
 * This class validates input data
 * 
 * @author Navigable Set
 * @version 1.0
 * @Copyright (c) Navigable Set
 */

public class DataValidator {
  /**
   * Checks if value is Null
   * 
   * @param val
   * @return
   */
  public static boolean isName(String val) {

    String name = "^[A-Za-z ]*$";
    /*
     * if (isNotNull(val)) { return val.matches(name);
     * 
     * } else { return false; }
     */
    if (val.matches(name)) {
      return true;
    } else {
      return false;
    }
  }
  
  
  public static boolean isRollNO(String val) {
    String passregex = "^([0-9]{2}[A-Z]{2}[0-9]{1,})\\S$";

    if (val.matches(passregex)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * Checks if value is Password
   * 
   * @param val
   * @return boolean
   */
  public static boolean isPassword(String val) {
    String passregex = "^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\\S])[A-Za-z0-9\\S]{6,12}$";

    if (val.matches(passregex)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * Checks if value is Phone No
   * 
   * @param val
   * @return boolean
   */
  public static boolean isPhoneNo(String val) {
    String regex = "^[7-9][0-9]{9}$";
    if (val.matches(regex)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * Checks if value is Null
   * 
   * @param val
   * @return boolean
   */
  public static boolean isNull(String val) {
    if (val == null || val.trim().length() == 0) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * Checks if value is NOT Null
   * 
   * @param val
   * @return
   */
  public static boolean isNotNull(String val) {
    return !isNull(val);
  }

  /**
   * Checks if value is an Integer
   * 
   * @param val
   * @return
   */

  public static boolean isInteger(String val) {

    if (isNotNull(val)) {
      try {
        int i = Integer.parseInt(val);
        return true;
      } catch (NumberFormatException e) {
        return false;
      }

    } else {
      return false;
    }
  }

  /**
   * Checks if value is Long
   * 
   * @param val
   * @return
   */
  public static boolean isLong(String val) {
    if (isNotNull(val)) {
      try {
        long i = Long.parseLong(val);
        return true;
      } catch (NumberFormatException e) {
        return false;
      }

    } else {
      return false;
    }
  }

  /*public static boolean isIntegerName(String val) {
    String match = "^[0-9]{3}$";

    if (val.matches(match)) {
      return true;
    } else {
      return false;
    }

  }*/

  /**
   * Checks if value is valid Email ID
   * 
   * @param val
   * @return
   */
  public static boolean isEmail(String val) {

    String emailreg = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    if (isNotNull(val)) {
      try {
        return val.matches(emailreg);
      } catch (NumberFormatException e) {
        return false;
      }

    } else {
      return false;
    }
  }

  /**
   * Checks if value is Date
   * 
   * @param val
   * @return
   * @throws ParseException
   */
  public static boolean isDate(String val) {

    Date d = null;
    if (isNotNull(val)) {
      d = DataUtility.getDate(val);
    }
    return d != null;
  }

  /**
   * Test above methods
   * 
   * @param args
   */


}

DataUtility Class

Data Utility is also a custom class that will help us to convert our data into a type like convert String data to int Set Date format etc.

package com.javawebapp.utility;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Data Utility class to format data from one format to another
 * 
 * @author Navigable Set
 * @version 1.0
* @Copyright (c) Navigable Set
 */

public class DataUtility 
{
  /**
   * Application Date Format
   */
  public static final String APP_DATE_FORMAT = "MM/dd/yyyy";

    //	public static final String APP_TIME_FORMAT = "MM/dd/yyyy HH:mm:ss";

  /**
   * Date formatter
   */
  private static final SimpleDateFormat formatter = new SimpleDateFormat(APP_DATE_FORMAT);

  //private static final SimpleDateFormat timeFormatter = new SimpleDateFormat(APP_TIME_FORMAT);

  /**
   * Trims and trailing and leading spaces of a String
   * 
   * @param val
   * @return
   */
  public static String getString(String val) {
    if (DataValidator.isNotNull(val)) {
      return val.trim();
    } else {
      return val;
    }
  }

  /**
   * Converts and Object to String
   * 
   * @param val
   * @return
   */
  public static String getStringData(Object val) {
    
    if (val != null) {
      return val.toString();
    } else {
      return "";
    }
  }

  /**
   * Converts String into Integer
   * 
   * @param val
   * @return
   */
  public static int getInt(String val) {
    if (DataValidator.isInteger(val)) {
      return Integer.parseInt(val);
    } else {
      return 0;
    }
  }

  /**
   * Converts String into Long
   * 
   * @param val
   * @return
   */
  public static long getLong(String val) {
    if (DataValidator.isLong(val)) {
      return Long.parseLong(val);
    } else {
      return 0;
    }
  }

  /**
   * Converts String into Date
   * 
   * @param val
   * @return
   */
   public static Date getDate(String val) {
          Date date = null;
          try {
              date = formatter.parse(val);
          } catch (Exception e) {

          }
          return date;
      }

  public static Date getDate1(String val) {
    Date date = null;
    
    try {
      date = formatter.parse(val);
      
    }catch(Exception e){}
    return date;
  }
  /**
   * Converts Date into String
   * 
   * @param date
   * @return
   */
  public static String getDateString(Date date) {
    
    try {
       if(date!=null) {
        return formatter.format(date);
      }
      else{
        return "";
      }
    } catch (Exception e) {
      return "";
    }
    
  }

  /**
   * Gets date after n number of days
   * 
   * @param date
   * @param day
   * @return
   */
  public static Date getDate(Date date, int day) {
    return null;
  }

  /**
   * Converts String into Time
   * 
   * @param cdt
   * @return
   */
  public static Timestamp getTimestamp(long l) {

    Timestamp timeStamp = null;
    try {
      timeStamp = new Timestamp(l);
    } catch (Exception e) {
      return null;
    }
    return timeStamp;
  }
  
  /**
   * Converts String into Time
   * 
   * @param cdt
   * @return
   */
  public static Timestamp getTimestamp(String cdt) {

    Timestamp timeStamp = null;
    try {
    //	timeStamp = new Timestamp((timeFormatter.parse(cdt)).getTime());
    } catch (Exception e) {
      return null;
    }
    return timeStamp;
  }
  /**
   * Converts Time into Long
   * 
   * @param tm
   * @return
   */
  public static long getTimestamp(Timestamp tm) {
    try {
      return tm.getTime();
    } catch (Exception e) {
      return 0;
    }
  }
  
  /**
   * Provide Current time
   * 
   * 
   * @return Time
   */
  public static Timestamp getCurrentTimestamp() {
    Timestamp timeStamp = null;
    try {
      timeStamp = new Timestamp(new Date().getTime());
    } catch (Exception e) {
    }
    return timeStamp;

  }



}

What you need to do!

Creare utility package and create two class DataValidator.java and DataUtility.java Copy and page the above code.