Spring MVC Date format validation with JSR303

前端 未结 2 1674
时光说笑
时光说笑 2021-01-07 11:12

I\'m using Spring MVC with JSR303 to do my input validation.

A form I\'ve created has a couple of date fields that are bound to Date objects within the

相关标签:
2条回答
  • 2021-01-07 11:52

    Thanks Ralph. I did some further digging around and came up with this (Which goes in my form controller):

        @InitBinder
        public void initBinder(WebDataBinder binder) {
    
    
        String format = "dd/MM/yyyy";
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        dateFormat.setLenient(false);
        CustomDateEditor customDateEditor = new CustomDateEditor(dateFormat,true,format.length());
    
        binder.registerCustomEditor(Date.class, customDateEditor);
        }
    

    With the properties file having the following key:

    typeMismatch.java.util.Date : Some nice calm reassuring message to assist all negligent users

    Maybe there are some other ways to do this but this will do for now.

    0 讨论(0)
  • 2021-01-07 11:52

    You can not do this with JSR303, because the validation runs on the already poplulated (form baching) object.

    So you need to implement your own custom converter, that is a bit more strickt than the one shipped with spring.

    @See Spring Reference: Chapter 6.5 Spring 3 Type Conversion

    0 讨论(0)
提交回复
热议问题