I would like to use javax.validation.constraints.Pattern for validation. The text should not be none or others.
Allowed Examples:
- something
- word
NOT allowed:
- none
- others
I am trying around but I dont catch my issue. Something like:
@NotNull
@Pattern(regexp = "(^none)")
String countryValue;
Thanks for your hint.
UPDATE:
As Anish said with the online regex validator, the regex ^(?!others|none) should be correct. But Spring-MVC still denied. Is there a special syntax to be used? I give more code to have a bigger picture:
Controller:
@PostMapping
public String post(@ModelAttribute @Valid DisclaimerFormDto disclaimerForm, BindingResult errors, ModelMap modelMap) {
if(errors.hasErrors()) {
errors.getAllErrors().forEach(System.out::println);
return "redirect:/disclaimer";
}
return "redirect:/product";
}
FormDto (with changes mentioned from Anish):
@Data
@ToString
public class DisclaimerFormDto {
@NotNull
@Pattern(regexp = "^(?!others|none)")
String countryValue;
}
Output of BindingResult:
Field error in object 'disclaimerFormDto' on field 'countryValue': rejected value [none]; codes [Pattern.disclaimerFormDto.countryValue,Pattern.countryValue,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [disclaimerFormDto.countryValue,countryValue]; arguments []; default message [countryValue],[Ljavax.validation.constraints.Pattern$Flag;@59374db6,^(?!(none|others)$).*$]; default message [muss auf Ausdruck "^(?!(none|others)$).*$" passen]

