Reputation: 191
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
}
Upvotes: 10
Views: 16105
Reputation: 31
use @DateTimeFormat
@RequestMapping(value = "/someTest")
public Object sendWishes(@RequestParam("birthDate") @DateTimeFormat(pattern="YYYYMMDD") LocalDate birthDate){ //Your code goes here }
Upvotes: 3
Reputation: 4541
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)
Upvotes: 1
Reputation: 10017
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
}
Upvotes: 10