Fork me on GitHub

Validation

Parameters validation

When using a parameter either as controller method argument or as a DTO field value, if you’re using one of the default supported type (see the Argument Extractors chapter for more information), it may produce a conversion error. For example when you are expecting an integer for your field but the given value contains characters.

In such cases, conversion issues are available in the validation-parameter by calling the validation.hasFieldViolations()-method in your controller which gives you a true or false. You have the ability to check which parameters caused the violations by using the getFieldViolations() method. Note that these violations must still be translated by using the messageKey attribute of each violation object.

Bean validation

Ninja uses Hibernate’s implementation of the javax.validation feature. This means that all JSR303-defined annotations work in your DTO objects when you let Ninja inject parameters into your controller. All you have to do is to set the @JSR303Validation annotation in front of your method-parameter and catch the result of the validation by injecting a Validation-parameter the same way.

An exemplary controller method would look like:

public Result postConfirmedPublication(
    @ProfileId String profileId,
    @JSR303Validation Dto dto, 
    Validation validation) {
        ...
}

In this example we want the context to be parsed as profileId and a Dto-object. Because of the leading @JSR303Validation-annotation all public fields in Dto may contain JSR303-annotations like this:

public class Dto {
        @Pattern(regexp = "[a-z]*")
        public String regex;
        @Size(min = 5, max = 10)
        public String length;
        @Min(value = 3)
        @Max(value = 10)
        public int range;
}

You can check the result of the validation by evaluating the validation-parameter by calling its validation.hasBeanViolations()-method in your controller which gives you a true or false. You have the ability to check which field(s) inside your Dto caused the violations by using the getBeanViolations() method which gives you a complete list of all occured violations in your Dto. With bean violations, the messageKey of each violation represents an interpolated message using the current locale.

JSR303 based validation is a generic approach that allows you to check the validity of submitted objects. These objects can be sent to your application via HTTP form submission, JSON or XML. The only important part is that your DTO objects contain valid JSR303 validation annotation which Ninja can evaluate.

The only important part is that your DTO objects contain valid JSR303 validation annotation which Ninja can evaluate.

If you want to validate nested DTOs or get in deeper detail, visit this great site: JBOSS Validation API