0

I would like to use the same form data class with two diferents controller but with different Validation pattern.

I have class and controller:

public class Query {
    @Pattern(regexp = "") //different pattern for askHim and askMe
    private String name;
}

@Controller
public class TestController {

    @PostMapping(value = "/api/askHim.html")
    public void askHim(@Valid @RequestBody Query q) {
        //do something
    }

    @PostMapping(value = "/api/askMe.html")
    public void askMe(@Valid @RequestBody Query q) {
        //do something
    }
}

How to use different pattern using same class for askHim method and askMe method?

Mr.M.
  • 78
  • 1
  • 6

1 Answers1

0

I already know. We need to use groups in validation and replace @Valid to @Validated.

public interface AskMe { }
public interface AskHim { }

public class Query {
    @Pattern(regexp = "name", groups = { AskMe.class })
    @Pattern(regexp = "age", groups = { AskHim.class })
    private String name;
}

@Controller
public class TestController {

    @PostMapping(value = "/api/askHim.html")
    public void askHim(@Validated({ AskHim.class }) @RequestBody Query q) {
        //do something
    }

    @PostMapping(value = "/api/askMe.html")
    public void askMe(@Validated({ AskMe.class }) @RequestBody Query q) {
        //do something
    }
}
Mr.M.
  • 78
  • 1
  • 6