0

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...

LuxuryMode
  • 33,401
  • 34
  • 117
  • 188
  • 1
    What is the actual code which doesn't work ? Maybe you should use forms to define user validation (a form is not only a UI component) – Julien Lafont Aug 15 '12 at 16:14
  • which data access layer are you using, ebean or anorm, or some other jpa? – mbseid Aug 15 '12 at 16:16
  • @JulienLafont yeah, i think im missing something basic here. could you point me in the direction of what form validations might look like when decoupled from any UI? – LuxuryMode Aug 15 '12 at 16:21
  • You can use a form to bind data (from html, WS, code ...) on a model object and trigger validation. It's one possible solution. – Julien Lafont Aug 15 '12 at 16:25
  • @JulienLafont, thanks. and what would that validation look like? – LuxuryMode Aug 15 '12 at 16:27

1 Answers1

0

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.

Julien Lafont
  • 7,869
  • 2
  • 32
  • 52
  • Thanks, Julien. So I'd simply use this form in my newUser action now? Instead of just directly persisting it to the db, I'd now make sure to use the form first and then if there's no errors, then insert. Is that the idea? – LuxuryMode Aug 15 '12 at 17:11
  • Exactly, and you can return a success/error message if the operation is ok/ko – Julien Lafont Aug 15 '12 at 17:22