deamon
deamon

Reputation: 92437

Domain object validation with Play! framework

I want to validate a domain object without automatic parameter binding to restrict the properties that can be set by the client.

The following class (example from Play! docs) ...

public class User {

    @Required
    public String name;

    @Required
    @Min(0)
    public Integer age;
}

... is usually validated like this

public static void hello(@Valid User user) {
   if(validation.hasErrors()) {
       params.flash();
       validation.keep();
       index();
   }
   render(user);
}

But in this scenario all fields of user can be set by the client.

Is it possible to trigger domain object validation (not "controller validation") with Play! 1.2 explicitly?

public static void hello(long id, String name) {
   User user = User.findById(id);
   user.name = name;

   user.validate(); // <-- I miss something like this 

   if(validation.hasErrors()) {
       params.flash(); 
       validation.keep(); 
       index();
   }
   render(user);
}

Upvotes: 4

Views: 1061

Answers (2)

axtavt
axtavt

Reputation: 242696

Have you tried

validation.valid(user);

Upvotes: 4

Pere Villega
Pere Villega

Reputation: 16439

You can add the @Required to the name parameter and turn the code into:

public static void hello(long id, @Required String name) {
   if(validation.hasErrors()) {
       params.flash(); 
       validation.keep(); 
       index();
   } 
   User user = User.findById(id);
   user.name = name;
   render(user);
}

You can extend the annotation to @Required(message="key.to.i18n.message") for I18N purposes.

Upvotes: 1

Related Questions