user3580890
user3580890

Reputation: 191

Can we validate @RequestParam value with a pattern

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

Answers (3)

abhishek chakrabartti
abhishek chakrabartti

Reputation: 31

use @DateTimeFormat

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

Upvotes: 3

Pramod S. Nikam
Pramod S. Nikam

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

Jaiwo99
Jaiwo99

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

Related Questions