Mic*_*ner 6 spring jpa spring-mvc
我想使用 javax.validation.constraints.Pattern 进行验证。文本不应是“无”或“其他”。
允许的示例:
不允许:
我正在尝试,但我没有意识到我的问题。就像是:
@NotNull
@Pattern(regexp = "(^none)")
String countryValue;
Run Code Online (Sandbox Code Playgroud)
谢谢你的提示。
更新:
正如 Anish 所说的在线正则表达式验证器,正则表达式^(?!others|none)应该是正确的。但Spring-MVC仍然否认。是否需要使用特殊的语法?我给出更多代码以获得更大的图景:
控制器:
@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";
}
Run Code Online (Sandbox Code Playgroud)
FormDto(包含 Anish 提到的更改):
@Data
@ToString
public class DisclaimerFormDto {
@NotNull
@Pattern(regexp = "^(?!others|none)")
String countryValue;
}
Run Code Online (Sandbox Code Playgroud)
绑定结果的输出:
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]
Run Code Online (Sandbox Code Playgroud)
尝试用这个:
@NotNull
// @Pattern(regexp = "^(?!others|none)")
// updated to take any kind of string to match.
@Pattern(regexp = "^((?!(none|others)).)*$")
private String countryValue;
Run Code Online (Sandbox Code Playgroud)
在这里检查这个正则表达式示例:^((?!(none|others)).)*$
测试用例 1:类似“abc”的字符串
截屏 :
测试用例 2:“abc other”、“abc none”、“none”或“words”等字符串
| 归档时间: |
|
| 查看次数: |
15734 次 |
| 最近记录: |