Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
like image 711
user3580890 Avatar asked May 14 '14 10:05

user3580890


People also ask

How do you validate a PATH variable?

Validating a PathVariable Let's consider an example where we validate that a String parameter isn't blank and has a length of less than or equal to 10: @GetMapping("/valid-name/{name}") public void createUsername(@PathVariable("name") @NotBlank @Size(max = 10) String username) { // ... }

Do @RequestParam has default value?

The default value of the @RequestParam is used to provide a default value when the request param is not provided or is empty. In this code, if the person request param is empty in a request, the getName() handler method will receive the default value John as its parameter.

Can we use @RequestParam in Get method?

Use the @RequestParam annotation to bind request parameters to a method parameter in your controller. AFAIK, request parameters are variables retrieved from query strings if the request method is GET. They are also the variables retrieved from the form values when the request method is POST.


1 Answers

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
  }
like image 66
Jaiwo99 Avatar answered Nov 15 '22 00:11

Jaiwo99