Java : Date Validation Against Multiple Formats

Input validation is a common step in every Java developer’s life. There were traditional ways of validating via splitting, parsing which later lead to regex and then annotations (frameworks). Recently, I was put forward a query to validate date in Java. Now, that’s a cake walk. We have Format classes with api to assist us in accomplishing this task. However, as with most project requirements; this had its twist and turns which required minor tweaking. So we arrive at our problem statement. It has some additions based on the requirements I got but the post will focus on validation against multiple formats.

Java_Date_Validation

Problem Statement

  1. This problem is a classic case of a data load validation process where a data source provider is sending date as per some format and we need to validate it before loading in our database or any other data system.
  2. Validate input strings for date formats.
  3. Date formats are pre-defined and can grow over a period of time with addition of any format supported by Java.
  4. Date format may be input by user. If yes, then validate against that format only.
  5. Return true or false as validation result.

Solution

  1. Doing this traditionally with SQL will make code verbose and difficult to maintain
  2. Further, its dependent on underlining system. If DB changes, the SQL might require some changes as well.
  3. Hence, Java comes as a good option.
  4. The following code snippet shows one way to validate a date in Java:
    SimpleDateFormat dateValObj = new SimpleDateFormat("dd/MM/yyyy");
    try {
    //An invalid date in variable "dateToValidate"; as per the above format will throw a ParseException
    Date date = dateValObj.parse(dateToValidate);
    } catch (ParseException e) {
    e.printStackTrace();
    return false;
    }
  5. Now, if you have multiple date formats, looping is an elegant option. Though, there could be other possible solutions; we implemented it by looping around a list which contains our permissible pre-defined date formats. Refer to the following snippet:
    SimpleDateFormat sdfObj = new SimpleDateFormat();
    boolean returnVal = false;
    //Loop through list of formats and validate using JAVA API.
    String patternVal = null;
    //validFormatsList is an array list of string containing formats against which validation will be performed.Eg : "MM/dd/yyyy"
    for (int i = 0; i < validFormatsList.size(); i++) {
    try {
         sdfObj.applyPattern(validFormatsList.get(i));
         sdfObj.parse(dateValue);
         returnVal = true;
         System.out.println("Looks like a valid date for Date Value :"+ dateValue + ": For Format:" + patternVal);
         break;
        } catch (ParseException e) {
         System.out.println("Parse Exception Occured for Date Value :"+dateValue+":And Format:"+patternVal);
         // e.printStackTrace();
        }
    }
    return returnVal;
  6. You must turn off(set to false) the setLenient option whenever validating dates in Java. This makes the validation process more stern and strict.
    sdfObj.setLenient(false);
  7. You should also check out ParsePosition class in Java and the corresponding parse method in SimpleDateFormat. You can implement that in the above code to remove try catch block.

The above solution can help you validate a string against multiple date formats.
In case you are looking a complete program that accepts input as string and pre-defined date formats; refer to the following files at github:

  1. Date_Formats.txt : Lists the formats against which input string should be validated.
  2. MultiFormatDateValidation : Core program validating input fields, populating date formats and validating input string to return whether it is valid date or not.

@Facebook

Subscribe to Blog via Email

Quick Enquiry

Leave a Reply

Your email address will not be published. Required fields are marked *