Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning validation errors as JSON with Play! framework

I want to build an application where forms are submitted via Ajax without a complete page reload. To display server-side validation errors the server should return validation errors as JSON and an appropriate HTTP status (400).

How can I accomplish this with the Play! framework?

like image 204
deamon Avatar asked Sep 29 '11 13:09

deamon


Video Answer


2 Answers

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 question is labeled with java tag, but I suppose this maybe useful for Scala developers.

like image 102
leonidv Avatar answered Nov 16 '22 02:11

leonidv


Are you looking for something more complex than this:

public static void yourControllerMethod() {
    ... // your validation logic

    if (validation.hasErrors()) {
       response.status = 400;
       renderJSON(validation.errors);
    }
}
like image 29
Tommi Avatar answered Nov 16 '22 03:11

Tommi