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?
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With