javaregexspringspring-mvcjpa

How to allow specific words using javax.validation.constraints.Pattern?


I would like to use javax.validation.constraints.Pattern for validation. The text should not be none or others.

Allowed Examples:

NOT allowed:

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]

Solution

  • Try with this :

    @NotNull
    // @Pattern(regexp = "^(?!others|none)")
    // updated to take any kind of string to match.
    @Pattern(regexp = "^((?!(none|others)).)*$")  
    private String countryValue;
    

    Check this regex example here: ^((?!(none|others)).)*$

    Test case 1 : String like "abc"

    Screenshot :

    enter image description here

    Test case 2 : Strings like "abc others", "abc none", "none" or "words"

    enter image description here