Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework 2: Best way of validating individual model fields separately

For this example, lets assume the user would like to update just the first name of his online profile.

Form:

<form data-ng-submit="updateFirstName()">
  <label for="firstName">First name<label>
  <input type="text" name="title" data-ng-model="firstName">
  <button type="submit">Update first name</button>
</form>

Controller:

public class UsersController {
  public static Result updateFirstName() {
    Form<User> filledForm = Form.form(User.class).bindFromRequest();

    // TODO: Validate firstName

    // if hasErrors() return bad request with errors as json

    // else save and return ok()
  }
}

Model:

@Entity
public class User extends Model {
  @Id
  public Long id;
  @Constraints.Required
  public String firstName;
  @Constraints.Required
  public String lastName;
}

How would one validate just one field at a time against the models constraints and return any resulting error messages back as json? This is quite a simple example, the real thing will have many fields (some very complex) together with a form for each.

like image 312
Hegemon Avatar asked Mar 17 '14 16:03

Hegemon


Video Answer


1 Answers

Play's in-built validation annotations conform to the Java bean validation specification (JSR-303). As a result, you can use the validation groups feature documented in the spec:

Model

@Entity
public class User extends Model {

  // Use this interface to mark out the subset of validation rules to run when updating a user's first name
  public interface FirstNameStep {}

  @Id
  public Long id;

  @Required(groups = FirstNameStep.class)
  public String firstName;

  // This isn't required when updating a user's first name
  @Required
  public String lastName;
}

Controller

public class UsersController {

  public static Result updateFirstName() {

    // Only run the validation rules that need to hold when updating a user's first name
    Form<User> filledForm = Form.form(User.class, User.FirstNameStep.class).bindFromRequest();

    if (form.hasErrors()) {
      // return bad request with errors as json
    }

    // else save and return ok()
  }
}

Validation groups are intended for your situation, where you have the same model object backing different forms, and you want to enforce different validation rules for the forms.

like image 59
avik Avatar answered Oct 20 '22 03:10

avik