10

i have a requirement, where in i need to validate my @RequestParam such that it is matched with my pattern

Example :

 @RequestMapping(value = "/someTest") public Object sendWishes(@RequestParam("birthDate") String birthDate) { // i need birthDate to be a valid date format in YYYYMMDD format // if its not valid it should not hit this method } 

3 Answers 3

10

It should be very easy:

 @RequestMapping(value = "/someTest?birthDate={birthDate}") public Object sendWishes(@Valid @Pattern(regexp = "you-pattern-here") @RequestParam("birthDate") String birthDate) { // i need birthDate to be a valid date format in YYYYMMDD format // if its not valid it should not hit this method } 
Sign up to request clarification or add additional context in comments.

1 Comment

The @Valid annotation is part of the standard JSR-303 Bean Validation API - this doesn't work in this case. ...now if it was a bean...
3

use @DateTimeFormat

@RequestMapping(value = "/someTest") public Object sendWishes(@RequestParam("birthDate") @DateTimeFormat(pattern="YYYYMMDD") LocalDate birthDate){ //Your code goes here } 

Comments

1

InitBinder will serve purpose. You Should have following init binding code in your controller:

@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMDD"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } 

after that you can get birthDate in your specified YYYYMMDD as date object:

@RequestMapping(value = "/someTest") public Object sendWishes(@RequestParam("birthDate") Date birthDate) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.