To perform server-side validation of your request, the Play Framework provides a built-in validation module that uses the Hibernate Validator under the hood.
Assuming you have a POJO class matching the incoming request,
import play.data.validation.Constraints; public class UserRequest{ @Constraints.Required private String userName; @Constraints.Required private String email; }
Request verification can be performed from the controller as follows.
public class UserController extends Controller{ Form<UserRequest> requestData = Form.form(UserRequest.class).bindFromRequest(); if(requestData.hasErrors()){ return badRequest(requestData.errorsAsJson()); } else{
The next request will be received if the request has not passed validation.
{ "userName": [ "This field is required" ], "email": [ "This field is required" ] }
In addition to this, you can apply several restrictions to the fields of the class. Some of them,
- @ Constraints.Min ()
- @ Constraints.Max ()
- @ Constraints.Email
Robin raju
source share