Home > Enterprise >  Date validator is not failing when it should
Date validator is not failing when it should

Time:01-11

I have a custom validator in my spring boot aplication, the validator is called, because I set a breakpoint and it stops.

The problem is the date validator is not working.

private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMYYYY"); 

@Override
public boolean isValid(String date, ConstraintValidatorContext ctx) {
    // TODO Auto-generated method stub
    if(date == null) {
        return true;
    }
    try {
        DATE_FORMAT.parse(date);
    } catch (Exception e) {
        return false;
    }
    return true;
}

I'm testing it with an invalid date 785454, but it does not go to the exception.

Where is my mistake?

CodePudding user response:

  1. fix pattern: SimpleDateFormat("MMyyyy")
  2. it add up the months:
new java.text.SimpleDateFormat("MMyyyy").parse("122000"); = Fri Dec 01 00:00:00 CET 2000
new java.text.SimpleDateFormat("MMyyyy").parse("132000"); = Mon Jan 01 00:00:00 CET 2001
new java.text.SimpleDateFormat("MMyyyy").parse("785454"); = Fri Jun 01 00:00:00 CEST 5460
new java.text.SimpleDateFormat("MMyyyy").parse("015454"); = Sun Jan 01 00:00:00 CET 5454
  1. the only exception you'll have to expect is ParseException - if the beginning of the specified string cannot be parsed. (see docs)

And the right solution (from comment): setLenientdocumentation and except

CodePudding user response:

From the docs Throws: NullPointerException - if text or pos is null.

It looks like the parse method throws exception only if the value given is null.

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

  •  Tags:  
  • Related