Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validation of Play 2.0 form (scala)

I'm writing a little hobby app. Now, in my application I want people to have a userId (just like mine is niklassaers here on stack overflow), and if it is already taken, I want the user to get an error so he can select another.

Here follows my Signup object, it gives me an error at the line "mapping(": "missing arguments for method mapping in object Forms; follow this method with `_' if you want to treat it as a partially applied function"

object Signup extends Controller {

  val userForm: Form[UserProfile] = Form(
    mapping(
      "userId" -> nonEmptyText,
      "passwordHash" -> nonEmptyText,
      "email" -> email
    ) verifying (
      "ThisIsATest", { case(userId, passwordHash, email) => true }
      // "UserID already taken", { DBService.exists(UserProfile.getClass().getName(), userId) }
      )(UserProfile.apply)(UserProfile.unapply))


  def index = Action {

    Ok(views.html.signup(userForm))
  }

  def register = Action { implicit request =>
    userForm.bindFromRequest.fold(
      errors => BadRequest(views.html.signup(errors)),
      user => Redirect(routes.Profile.index))
  }
}

As you can see, I've replaced my lookup service with a test verification that simply returns true, to make the example less complex. For completeness, this is my UserDetail case class:

case class UserProfile(
                   userId : String,
                   email: String,
                   passwordHash: String)

I'm a Scala newbie and Play newbie, so I'm sorry if this is a very trivial question. But:

  1. What am I doing wrong since I get this error?

  2. Is this the right way of adding my own validation?

  3. Follow-up question: I redirect if it goes well, but how should I redirect to a page referencing the just verified form?

Cheers

Nik

like image 986
niklassaers Avatar asked Jan 16 '23 11:01

niklassaers


1 Answers

Finally got around this: verifying isn't something that comes after mapping, it is something that comes at the constraint. So it should be

"userId" -> nonEmptyText.verifying( "UserID already taken", userId => DBService.exists(UserProfile.getClass().getName().replace("$", ""), userId) == false ),

I hope this helps others that have the same problem :-)

like image 124
niklassaers Avatar answered Jan 20 '23 15:01

niklassaers