Return validation errors as JSON with Play! framework

I want to create an application in which forms are submitted via Ajax without a full page reload. To display validation errors on the server side, the server must return validation errors as JSON and the corresponding HTTP status (400).

How can I accomplish this using Play! framework?

+7
source share
4 answers

You are looking for something more complex than this:

public static void yourControllerMethod() { ... // your validation logic if (validation.hasErrors()) { response.status = 400; renderJSON(validation.errors); } } 
+6
source

In Play Framework 2.x and Scala, you can use this example:

 import play.api.libs.json._ case class LoginData(email : String, password: String) implicit object FormErrorWrites extends Writes[FormError] { override def writes(o: FormError): JsValue = Json.obj( "key" -> Json.toJson(o.key), "message" -> Json.toJson(o.message) ) } val authForm = Form[LoginData](mapping( "auth.email" -> email.verifying(Constraints.nonEmpty), "auth.password" -> nonEmptyText )(LoginData.apply)(LoginData.unapply)) def registerUser = Action { implicit request => authForm.bindFromRequest.fold( form => UnprocessableEntity(Json.toJson(form.errors)), auth => Ok(Json.toJson(List(auth.email, auth.password))) ) } 

I see that this question is tagged with java, but I suggest that this might be useful for Scala developers.

+6
source

See the samples and tests folder and validation application. One example (Sample7) does exactly what you need using the special jQueryValidate tag (which you can see in the example).

If you try the sample, you will see that this is a pretty neat solution, and in my opinion, this verification method should be part of Core Playframework.

+4
source

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{ //... successful validation } } 

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
+1
source

All Articles