Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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]
like image 396
Michael Hegner Avatar asked Jun 27 '26 01:06

Michael Hegner


1 Answers

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

like image 141
Anish B. Avatar answered Jun 28 '26 16:06

Anish B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!