Skip to content

Instantly share code, notes, and snippets.

@mloza
Last active December 2, 2020 21:27
Show Gist options
  • Save mloza/bb7a929399e37894afaf2f118d434ddc to your computer and use it in GitHub Desktop.
Save mloza/bb7a929399e37894afaf2f118d434ddc to your computer and use it in GitHub Desktop.
Kod źródłowy do wpisu o niestandardowych walidatorach dla Java Bean Validation, znajdującego się na blogu https://blog.mloza.pl/java-bean-validation-niestandardowy-walidator-danych/
@RestController
public class CustomValidatorController {
@PostMapping("/zipCode")
@ResponseBody
public String zipCodeBody(
@RequestBody @Valid RequestWithZipCode body // #1
) {
return "OK! Everything is valid";
}
}
@WebMvcTest
public class CustomValidatorControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper objectMapper;
@Test
public void shouldReturnErrorWhenInputIsInvalid() throws Exception {
mvc.perform(post("/zipCode")
.contentType(MediaType.APPLICATION_JSON)
.content(invalidBody()))
.andDo(mvcResult -> System.out.println(mvcResult.getResponse().getContentAsString()))
.andExpect(status().isBadRequest());
}
@Test
public void shouldReturnOkWhenInputIsValid() throws Exception {
mvc.perform(post("/zipCode")
.contentType(MediaType.APPLICATION_JSON)
.content(validBody()))
.andDo(mvcResult -> System.out.println(mvcResult.getResponse().getContentAsString()))
.andExpect(status().is2xxSuccessful());
}
private String invalidBody() throws JsonProcessingException {
return objectMapper.writeValueAsString(
new RequestWithZipCode("1-21"));
}
private String validBody() throws JsonProcessingException {
return objectMapper.writeValueAsString(
new RequestWithZipCode("31-521"));
}
}
public class RequestWithZipCode {
@ZipCode // #1
private String zipCode;
// geter, seter, konstruktory...
}
@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = ZipCodeValidator.class). // #1
@Documented
public @interface ZipCode {
String message() default "Podany kod pocztowy jest nieprawidłowy"; // #2
Class<?>[] groups() default {}; // #3
Class<? extends Payload>[] payload() default {}; // #4
}
public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
Pattern pattern = Pattern.compile("^[0-9]{2}-[0-9]{3}$");
return pattern.matcher(value).matches();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment