Spring 验证和@Valid

Spring validation and @Valid

我有控制器的方法:

@RequestMapping(value="/eusers", method=RequestMethod.POST)
    public @ResponseBody String createEUser(@Valid @RequestBody EUser e, BindingResult result){
            if(result.hasErrors()){
                return "error";
            }
            //EUser creation and adding to a DB
            return "OK";
    }

EUser.java 如下:

@Entity
@Table(name="users")
public class EUser {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Max(5)
    @Column(name="name")
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

问题是当我传递包含少于 5 个字符的参数时("asd" 在这种情况下)我收到了验证错误消息:

org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'euser' on field 'name': rejected value [asd]; 
codes [Max.user.name,Max.name,Max.java.lang.String,Max]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [euser.name,name]; 
arguments []; default message [name],5]; 
default message [must be less than or equal to 5]

但是 asd 字符串是有效的!怎么了?在错误消息中我们可以看到 rejected value [asd];。为什么?

@Max 用于数字。您应该使用 @Size 来验证字符串长度。

Bean 验证未指定对字符串使用 @Max。来自休眠验证 documentation:

Hibernate Validator allows some constraints to be applied to more data types than required by the Bean Validation specification (e.g. @Max can be applied to Strings). Relying on this feature can impact portability of your application between Bean Validation providers.

因此,尝试使用 @Size,像这样,以符合所有提供商的要求:

@Column
@Size(max=5)
private String name;