Search code examples
scalaplayframeworksqueryl

How do I implement User validations in Play!?


I have a User model, the scheme for which looks like this:

# --- First database schema

# --- !Ups

create sequence s_user_id;

create table user (
  id  bigint DEFAULT nextval('s_user_id'),
  firstName  varchar(128),
  lastName  varchar(128),
  email  varchar(128) unique
);


# --- !Downs

drop table user;
drop sequence s_user_id;

How can I validate the new users instead of just crashing with a

RuntimeException: Exception while executing statement : Unique index or primary key violation:

?

Also, I'm not using any forms or views of any kind. I'm just creating an API...


Solution

  • You can use the forms to define and trigger your validation rules.

    Note that you can use forms without UI, the data can became from what you want (WS, code, html ...)

    For exemple :

    case class User(name: String, age: Int)
    
    val userForm = Form(
      mapping(
        "name" -> text.verifying(required),
        "age" -> number.verifying(min(0), max(100))
      ) verifying("Your custom validation", fields => fields match { 
          case (n, a) => User.myCustomValidation(n,a) 
      }) (User.apply)(User.unapply)
    )
    
    val filledForm = userForm.fill(User("Bob", 18))
    if (filledForm.hasErrors) {
     // or filledForm.fold
    }
    

    See the ScalaForms documentation for more details, or a more complex exemple.