[英]Spring annotation for form validation for issue?
Sorry for asking the simple question. 很抱歉问这个简单的问题。 I searched a lot , but can't find the exact solution.
我进行了很多搜索,但找不到确切的解决方案。
In my spring bean class I have int field like (private int id) . 在我的spring bean类中,我有int字段,例如(private int id)。 I used
@NotEmpty
annotion. 我使用了
@NotEmpty
注释。
I need to allow only numbers not any alphabets or string in the input field. 我只需要在输入字段中允许数字而不是任何字母或字符串。 What annotation I need to use.
我需要使用什么注释。
I have tried the @NumberFormat(style = Style.NUMBER)
, @Digits(fraction = 0, integer = 5)
annotations and nothing working out. 我尝试了
@NumberFormat(style = Style.NUMBER)
, @Digits(fraction = 0, integer = 5)
@NumberFormat(style = Style.NUMBER)
@Digits(fraction = 0, integer = 5)
批注,但没有任何结果。
Please suggest me the solution or any example for form validation... 请给我建议解决方案或表单验证的任何示例...
I suggest you to read the relevant part of the reference carefully. 我建议您仔细阅读参考资料的相关部分 。 You create your validator which implements the Validator interface:
您创建实现Validator接口的验证器:
public class FooValidator implements Validator {
/**
* This Validator validates *just* Foo instances
*/
public boolean supports(Class clazz) {
return Foo.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Foo foo = (Foo) obj;
if (!isNumeric(foo.getFieldThatShouldBeNumeric())
{
e.rejectValue("fieldThatShouldBeNumeric", "notnumeric");
}
}
}
then inject it, either 'locally' to the controller itself: 然后将其“本地”注入控制器本身:
@Controller
public class MyController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new FooValidator());
}
@RequestMapping("/foo", method=RequestMethod.POST)
public void processFoo(@Valid Foo foo) { ... }
or 'globally': 或“全局”:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven validator="globalValidator"/>
</beans>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.