开发者

Play Framework: How to validate a subset of fields in an object?

I have an User object that has many attributes. In my edit profile screen I'm displaying a subset of those attributes. In the corresponding controller action how can开发者_如何学运维 I validate only those fields that are being edited and not all the fields in the User object?

I have annotated the fields in the User object with the MaxSize, Email, URL, etc. constraints and don't want to repeat them again by validating each field manually.

Any pointers would be greatly appreciated. Thanks!


the simplest way is to pass the full object to the receiving method and just validate all of it. As you are only editing a subset of fields, they will be the only ones changing and the ones that will trigger an error if the validation fails. This is, of course, assuming that you never store invalid objects in the database!

If not, you can also create a support bean that doesn't extend from Model, with validation tags, and pass that to the form and controller. Something like:

public class SupportBean {
   @Email
   public String mail;
   @Max(3)
   public int size;
   //etc, add getters and setters as I'm not sure if it is required.
}

In both cases it would be something like this, replacing the full object User by a temporary object if needed (double check the code, I don't have Play environment here and I may do some typos/small mistakes)

*{ assuming parameter 'user' is passed in the render method that creates this view }*
#{form @controller.save()}
  #{field 'user.name'}
    <p>
      <label>&{field.name}</label>
      <input type="text" id="${field.id}" name="${field.name}" value="${field.value}"  class="${field.errorClass}">
      <span class="error">${field.error}</span>
    </p>
  #{/field}
  *{ add more field the same way }*
#{/form}

And then in the controller:

*{ we tag required for validation }*
public static void save(@Valid User user) {
   checkAuthenticity();
   if(validation.hasErrors()){
     //there are errors, add to flash and redirect to edit page
   } else {
     user.save();
     //redirect
   }
}

Add a POST rule to 'save' int he routes file, and you are ready to go.

The framework has a sample project (validation I think its the name) which contains 7 different ways of doing validation. The last one uses JQuery to reuse the validation tags of your class and run the same validation in the client before committing. Give them a look, they may help you a lot :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜