Validations & Scala

139 views
Skip to first unread message

Kevin Scaldeferri

unread,
Mar 26, 2012, 5:34:48 PM3/26/12
to dropwiz...@googlegroups.com
Are there any general suggestions on how to employ validations with Scala representation classes?  I had hopes that this sort of this would work, but it seems to be completely ignored:

case class GiftCertificate(
 @Range(min=1,max=2000) amount: Int,
 @NotEmpty senderName: String,
 @NotEmpty recipientName: String,
 @NotEmpty recipientEmail: String,
...
)

and in the resource:

@PUT
 def create(@Valid giftCertificate: GiftCertificate): Response = ...


From doing some reading about Hibernate, it appears like it will only work if you have a no-args constructor and getter/setters with annotations, which seems a little gross in Scala.  I've also tried the approach of adding require()s to the constructor, but that produces a 500 error rather than 422.  Right now I've defined a isValid method and I'm calling that as the first line of the create() method in the resource.

Does anyone have advice or recommendations on the best way to do this?

Thanks,

-kevin

Coda Hale

unread,
Mar 26, 2012, 6:41:39 PM3/26/12
to dropwiz...@googlegroups.com
You'll need to declare them as @BeanProperty, IIRC, to ensure getAmount() etc exists.

No-arg constructors are not required at all — the validator just validates; it's Jackson that does the creating (and Jerkson that handles case classes).

If you'd like require() to return a 422, you'll need to implement a Jersey exception mapper to map IllegalArgumentExceptions to your desired responses.

---
Coda Hale
http://codahale.com

Kevin Scaldeferri

unread,
Mar 26, 2012, 6:53:29 PM3/26/12
to dropwiz...@googlegroups.com
I forgot to mention that I did try adding @BeanProperty but it did not seem to help.  I just tried again:

case class GiftCertificate(
  @BeanProperty @Range(min=1,max=2000) amount: JInteger,
  @BeanProperty @NotEmpty senderName: String,
  @BeanProperty @NotEmpty recipientName: String,
  @BeanProperty @NotEmpty recipientEmail: String,
...

And the validation was not applied.  Is there some other variation on this that I ought to be trying?

Thanks,

-kevin

Coda Hale

unread,
Mar 27, 2012, 10:06:44 AM3/27/12
to dropwiz...@googlegroups.com
I think you may not be able to use case classes and validations, then. If you can't apply an annotation to the underlying field or synthetic getter, you're hosed.

---
Coda Hale
http://codahale.com

Reply all
Reply to author
Forward
0 new messages