1

I have controller's method:

@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 is the following:

@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;
    }
}

The issue is when I even pass the pararmeter which contains less than 5 characters ("asd" in the case) I got the validation error message:

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]

But the asd string is valid! What's wrong? In the error message we can see that rejected value [asd];. Why?

1
  • Don't use @Max for Strings validation,try to make use of @Length(min = 1, max = 5) or @Size(max=5) annotations. Commented Jan 11, 2015 at 12:33

2 Answers 2

4

Bean validation does not specify use of @Maxfor strings. From hibernate validation 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.

So, try use @Size, like this, for compliance with all providers:

@Column
@Size(max=5)
private String name;
Sign up to request clarification or add additional context in comments.

Comments

3

@Max is for numbers. You should use @Size to validate string length.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.