2
votes

Dear Playframework users.

I have switched to play framework 2.2 and I have a question on validation. I hope someone can point me to the right direction.

I have a controller to fetch a collection.

GET        /country  controllers.api.CountryController.list(fetchInactive: Int ?= 0, sortBy: String ?= "name", sortDir: String ?= "asc" )

public static Result list( int fetchInactive, String sortBy, String sortDir)

it works great, although I would like to LIMIT the possible values one can send as sortBy field directive.

E.g. a list of elements. like 'name','id' etc. In play 1 it is very easy to validate controller parameters. see Play Framework: automatic validation of controller methods applied?

I know how to use JSR-303 with Models, although here this is an API and I want to validate the individual parameters.

Could someone give me a hint or a example how I can achieve that?

I would like to use annotations to define my own validator to validate that sortBy only accepts certain strings values.

Thanks in advance,

1

1 Answers

0
votes

Actually in this case you should use default values for sortBy and sortDir if user gives something out of allowed range, you can do it easily within the action (don't need to use validator)

public static Result list(Integer fetchInactive, String sortBy, String sortDir) {
    Integer resolvedFetchInactive
            = (fetchInactive != null && Arrays.asList(0, 1, 2).contains(fetchInactive)) ? fetchInactive : 0;

    String resolvedSortBy
            = (sortBy != null && Arrays.asList("name", "id").contains(sortBy)) ? sortBy : "name";

    String resolvedSortDir
            = (sortDir != null && Arrays.asList("asc", "desc").contains(sortDir)) ? sortDir : "asc";

    if (!resolvedSortBy.equals(sortBy) || !resolvedSortDir.equals(sortDir) || !resolvedFetchInactive.equals(fetchInactive)) {
        //redirect to the same list with allowed values
        return redirect(routes.Application.list(resolvedFetchInactive, resolvedSortBy, resolvedSortDir));
    }

    return ok("You're going to display list sorted by: " + resolvedSortBy + " " + resolvedSortDir + ", fetchInactive is: " + resolvedFetchInactive);
}