playframework-2.5

How to validate a form in play framework


I want do validate a form after filling with a json object. By stepping throw the code I see the correct values in the Post Object but I will get no errors if the title is under 5 chars. Why, had some one an idea?

@Constraints.Required
@Constraints.MinLength(5)
private String title;

Post post = Json.fromJson(json, Post.class);                            
if(postForm.hasErrors()){

Solution

  • /*
    example
    */
    private FormFactory formFactory;
    
        @Inject
        YourContructor(FormFactory formFactory){
            this.formFactory
        }
    
        @BodyParser.Of(value = BodyParser.Json.class)
    
     public static Result create() {
    
            JsonNode json = request().body().asJson();
    
           Form<Post> post= formFactory.form(Post.class).bind(json);
            if(post.hasErrors()){
                return badRequest(post.errorsAsJson());
        }
    
            return ok(json);
        }