模型....
@Digits(integer=5, fraction=0, message="The value must be numeric and less than five digits")
private int value;
Run Code Online (Sandbox Code Playgroud)
豆文件....
<mvc:annotation-driven />
Run Code Online (Sandbox Code Playgroud)
控制器....
@RequestMapping(value = "/admin/save.htm", method = { RequestMethod.POST })
public ModelAndView saveSection(@Valid @ModelAttribute Section section, BindingResult result) {
if(result.hasErrors()) {
return new ModelAndView("admin/editSection", "section", section);
}
Run Code Online (Sandbox Code Playgroud)
如何将"价值"限制在数字范围内?如果我输入的不是数字,我会收到此错误:
无法将类型为java.lang.String的属性值转换为属性值所需的java.lang.Integer类型; 嵌套异常是org.springframework.core.convert.ConversionFailedException:无法将类型java.lang.String中的值"A"转换为java.lang.Integer类型; 嵌套异常是java.lang.IllegalArgumentException:无法解析A.
我看过一些提到initBinding的帖子,但我不确定如何使用它,或者它是否会帮助我.这必须在以前解决.有没有办法确保它在绑定之前是一个数字?
或者,如果有人可以发布正确的messages.properties条目来覆盖此错误,那也可能对我有用.
I tried @Pattern but that doesn't work on ints
我正在尝试通过Spring 3.0为Hibernate Validator 4.1设置自定义消息源.我已经设置了必要的配置:
<!-- JSR-303 -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
翻译是从我的消息源提供的,但似乎消息源中的替换令牌在消息源中被查找,即:
my.message=the property {prop} is invalid
Run Code Online (Sandbox Code Playgroud)
有人要求在messageSource中查找"prop".进入ResourceBundleMessageInterpolator.interpolateMessage我注意到javadoc说:
根据JSR 303中指定的算法运行消息插值.
注意:用户捆绑包中的查找是递归的,而默认捆绑包中的查找则不是!
在我看来,对于用户指定的bundle总是会发生递归,所以实际上我无法翻译像Size那样的标准消息.
如何插入我自己的消息源并能够在消息中替换参数?
当点击一个按钮时,如何跳过使用JSF的JSR-303 Bean验证?
解释一些方法有点冗长的问题......考虑一个表单中的列表:
<h:form id="form">
<h:commandButton value="Add row">
<f:ajax execute="foo" listener="#{bean.add()}" render="foo" />
</h:commandButton>
<h:dataTable id="foo" var="foo" value="#{bean.foos}">
<h:column>
Name: <h:inputText id="field" value="#{foo.name}" required="true" />
<h:messages for="field" />
</h:column>
<h:column>
<h:commandButton value="Remove">
<f:ajax execute=":form:foo" listener="#{bean.remove(foo)}" render=":form:foo" />
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
Run Code Online (Sandbox Code Playgroud)
当用户单击添加或删除行时,操作应该在没有验证的情况下执行.问题是,JSF重新呈现整个列表并尝试验证它.如果存在未验证的草稿更改,则会发生验证错误,并且永远不会调用侦听器方法(因为验证失败会阻止该操作).但是,添加immediate="true"到f:ajax允许方法执行,尽管有验证错误.但是,验证错误仍然会发生并显示在此处.
我看到两个选择:
1)使用immediate ="true"并且不显示验证错误
对于非验证按钮,设置immediate ="true"和h:消息:
<h:messages rendered="#{param['SHOW_VALIDATION']}" />
Run Code Online (Sandbox Code Playgroud)
然后设置保存按钮(实际上应该尝试保存表单)以发送该参数:
<h:commandButton>
<f:param name="SHOW_VALIDATION" value="true" />
</h:commandButton>
Run Code Online (Sandbox Code Playgroud)
这会导致验证,但除非SHOW_VALIDATION存在参数,否则不会显示消息.
2)有条件地在facelets中声明验证:
<h:inputText>
<f:validateRequired disabled="#{!param['VALIDATE']}" />
</h:inputText>
Run Code Online (Sandbox Code Playgroud)
并保存按钮:
<h:commandButton>
<f:param name="VALIDATE" value="true" />
</h:commandButton>
Run Code Online (Sandbox Code Playgroud)
这会导致字段仅在VALIDATE参数存在时进行验证(=按下保存按钮时).
但这些似乎都是一种黑客攻击.我怎样才能简单地使用JSR-303 Bean验证,但在声明时跳过它?
如何@Pattern在非强制表单字段上使用约束?
@Pattern(regexp="...")
private String something;
Run Code Online (Sandbox Code Playgroud)
一旦我提交表单,我就会得到预期的验证错误,但是用户可能会将该字段留空,因为这不是必填字段.
PS:我可以编写自己的约束注释.但是,我只想问一种更简单的方法来组合注释或添加注释属性.JSR303实现是hibernate-validator.
我有一个名为User的实体,我想验证手机号码字段
手机号码字段不是强制性的,可以留空,但应该是10位数字.
如果用户输入的长度小于10位,则应抛出错误.
以下是我的用户类.
public class User {
@Size(min=0,max=10)
private String mobileNo;
}
Run Code Online (Sandbox Code Playgroud)
当我如上所述使用@Sized注释时,我可以验证大于10的值,但如果用户输入的数字少于10位,则不会引发错误.
我的要求是,如果用户将mobileNo字段留空,该字段有效,但如果输入了值,则验证应确保输入的数字仅为10位数和10位数.
我应该使用哪个注释来满足此要求?
我有一个名为Browser的POJO,我用Hibernate Validator注释进行了注释.
import org.hibernate.validator.constraints.NotEmpty;
public class Browser {
@NotEmpty
private String userAgent;
@NotEmpty
private String browserName;
...
}
Run Code Online (Sandbox Code Playgroud)
我编写了以下单元测试,试图验证我的Controller方法是否捕获了验证错误.
@Test
public void testInvalidData() throws Exception {
Browser browser = new Browser("opera", null);
MockHttpServletRequest request = new MockHttpServletRequest();
BindingResult errors = new DataBinder(browser).getBindingResult();
// controller is initialized in @Before method
controller.add(browser, errors, request);
assertEquals(1, errors.getErrorCount());
}
Run Code Online (Sandbox Code Playgroud)
这是我的Controller的add()方法:
@RequestMapping(value = "/browser/create", method = RequestMethod.POST)
public String add(@Valid Browser browser, BindingResult result, HttpServletRequest request) throws Exception {
if (result.hasErrors()) {
request.setAttribute("errorMessage", result.getAllErrors());
return …Run Code Online (Sandbox Code Playgroud) 我使用Bean Validation 1.2使用以下方法创建了一个Spring MVC REST服务:
@RequestMapping(value = "/valid")
public String validatedMethod(@Valid ValidObject object) {
}
Run Code Online (Sandbox Code Playgroud)
如果object无效,Tomcat会通知我,The request sent by the client was syntactically incorrect.我validatedMethod的调用永远不会被调用.
如何获取ValidObjectbean 中定义的消息?我应该使用一些过滤器或拦截器吗?
我知道我可以像下面一样重写,ConstraintViolation从注入中得到一组s Validator,但上面看起来更整洁......
@RequestMapping(value = "/valid")
public String validatedMethod(ValidObject object) {
Set<ConstraintViolation<ValidObject>> constraintViolations = validator
.validate(object);
if (constraintViolations.isEmpty()) {
return "valid";
} else {
final StringBuilder message = new StringBuilder();
constraintViolations.forEach((action) -> {
message.append(action.getPropertyPath());
message.append(": ");
message.append(action.getMessage());
});
return message.toString();
}
}
Run Code Online (Sandbox Code Playgroud) 使用Bean Validation 2.0,还可以对容器元素设置约束.
我无法使用Kotlin数据类:
data class Some(val someMap: Map<String, @Length(max = 255) String>)
Run Code Online (Sandbox Code Playgroud)
这没有任何效果.有任何想法吗?
我创建了一个包含示例项目的存储库来重现案例:https://github.com/mduesterhoeft/bean-validation-container-constraints
对不起,如果这个问题已在某处提到过.如果有请链接我,我还没有找到一个满意的答案.
我一直在寻找一种方法让我的javax验证提供的错误消息更具体.
我目前拥有的@Min注释消息在ValidationMessages.properties文件中指定:
javax.validation.constraints.Min.message=The value of this variable must be less than {value}.
Run Code Online (Sandbox Code Playgroud)
这打印出来就像预期的那样
The value of this variable must be less than 1
Run Code Online (Sandbox Code Playgroud)
我想要的是消息还包括验证失败的变量(和类)的名称以及失败的变量的值.更像是.
The value of class.variable was 0 but not must be less than 1
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
克利
是否有一个验证标注为春,会做这样的:
@ValidString({"US", "GB", "CA"})
final String country;
Run Code Online (Sandbox Code Playgroud)
并验证字符串是数组中支持的值之一?
bean-validation ×10
java ×6
spring-mvc ×5
spring ×4
validation ×3
facelets ×1
jsf ×1
jsf-2 ×1
junit ×1
kotlin ×1
min ×1
phone-number ×1