Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check validation directly on the model

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.

like image 965
Richard N. Avatar asked Jan 17 '23 00:01

Richard N.


2 Answers

You can define a validate method on your Java model classes. See the corresponding documentation.

like image 186
Julien Richard-Foy Avatar answered Jan 28 '23 22:01

Julien Richard-Foy


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();
    }

}
like image 36
Berk Avatar answered Jan 28 '23 21:01

Berk