【问题标题】:Spring annotation for form validation for issue?用于问题的表单验证的 Spring 注释?
【发布时间】:2013-01-01 22:57:04
【问题描述】:

很抱歉问了这么简单的问题。我搜索了很多,但找不到确切的解决方案。

在我的 spring bean 类中,我有 int 字段,例如 (private int id) 。我使用了@NotEmpty 注释。

我需要在输入字段中只允许数字而不是任何字母或字符串。我需要使用什么注释。

我已经尝试了 @NumberFormat(style = Style.NUMBER)@Digits(fraction = 0, integer = 5) 注释,但没有任何结果。

请向我推荐表单验证的解决方案或任何示例...

【问题讨论】:

  • 到底是什么问题? Spring允许您在绑定到int的字段中输入任意字符?你确定吗?
  • @axtavt 感谢您的支持。我的需要是只允许文本字段中的数字。如果我输入任何字符串,如“eee”或 34ue,我需要将错误消息显示为“仅允许数字”。我应该使用什么?
  • Spring 不应该允许你在那里输入任意字符串。如果您需要自定义错误消息,请参阅stackoverflow.com/questions/4082924/…
  • @Anand Spring 本身无法将字符串绑定到整数。无需注释!它会像这样抛出 ParseException 或 smth。

标签: java spring javabeans spring-annotations


【解决方案1】:

我建议你仔细阅读relevant part of the reference。 您创建实现 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");
    }
}
}

然后将其“本地”注入到控制器本身:

@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) { ... }

或“全局”:

<?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>

【讨论】:

  • 你好。可能是一个伟大的目标。但是我应该从某个地方导入 isNumeric 吗?
猜你喜欢
  • 1970-01-01
  • 2021-12-09
  • 2012-06-27
  • 2011-06-21
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多