Reputation: 34884
I have the following code in a controller:
val addForm = Form(
tuple("email" -> nonEmptyText, "password" -> nonEmptyText)
)
def add = Action { implicit request =>
Ok(views.html.registration.add(addForm))
}
def create = Action { implicit request =>
addForm.bindFromRequest.fold(
failure => //....,
success => //....
At create
(? or anywhere else it makes sense) method I want to check some additional conditions, for example, whether an email already exists in a db. And if it does, return an error to a view says "this email already exists".
I didn't find anything about it at the Play's documentation, only about the standard restrictions like "nonEmpty".
Where and how do I do this?
Upvotes: 0
Views: 125
Reputation: 23841
Try this:
import play.api.data.Mapping
import play.api.data.Forms._
import play.api.data.validation._
val addForm = Form(
tuple("email" -> freeEmail, "password" -> nonEmptyText)
)
def freeEmail: Mapping[String] = {
nonEmptyText verifying Constraint[String]("constraint.email") { o: String =>
if (Email.exists(o) /*your checker here*/) Invalid(ValidationError("Email already exists")) else Valid
}
}
Upvotes: 2