I have just started to "play" with Play framework (2.0) and I'm having some trouble to find a solution to validate models directly. I have googled the problem but I can't find any examples.
In Rails you can check if a model is valid by writing like this: my_model.valid?
I have only seen examples where I can validate the models in the controller but that's not what I want to do right now when I'm writing unit tests.
It would be nice to have myModel.isValid(); or something similar.
You can define a validate
method on your Java model classes. See the corresponding documentation.
You can use this solution with some modifications.
In the model:
package models;
import play.data.validation.Constraints;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.HashSet;
import java.util.Set;
public class TestModel {
@Constraints.Required
public String requiredField;
// method for directly models validation
public static Set<String> validate(Object object, Validator validator) {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
Set<String> errors = new HashSet<>();
for(ConstraintViolation<Object> cv : constraintViolations) {
errors.add(cv.getMessage());
}
return errors;
}
}
In the controller:
package controllers;
import models.TestModel;
import play.data.validation.Validation;
import play.mvc.Controller;
import play.mvc.Result;
import java.util.Set;
public class Test extends Controller {
public static Result test() {
TestModel testModel = new TestModel();
Set<String> errors = TestModel.validate(testModel, Validation.getValidator());
if(!errors.isEmpty()) {
return badRequest();
}
return ok();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With