Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does scala suport JSR-303 validation?

Does scala supports JSR-303 validation?

If it does - could you please write an example?

If it does not - are there workarounds to run JSR-303 validation on scala classes?

like image 426
Cherry Avatar asked Feb 12 '23 17:02

Cherry


1 Answers

There is good news and bad news.

The good news is that you can use JSR-303 annotations in your Scala code with no problems.

Here is an example from a previous project of mine, where all of the annotations are JSR-303 annotations, some of them out of the box, some of them custom.

@MessagesValid
class Messages {
  @NotEmpty @Valid
  private var msgs: java.util.List[DeliveredMessage] = _  
  def messages = msgs.asScala

  @ChannelValid 
  var channel: String = _

  var emailFrom: String = _
  var emailReplyTo: String = _

  @PublishAtValid
  var publishAt: String = _
}

Note how the msgs collection is a java.util.List. It needs to be a Java collection for the @NotEmpty and @Valid to work. But it's easy enough to expose that field as a Scala collection using JavaConverters.

The bad news is that you cannot create a JSR-303 annotation using Scala. You must write those annotations using Java. So you will need to have a mixed Scala/Java project if you want to write custom JSR-303 annotations.

There is an old bug (bug #32!) in the Scala bug tracker to support these types of annotations but it is currently closed as Won't Fix. Please vote for it anyway.

like image 177
sourcedelica Avatar answered Feb 19 '23 11:02

sourcedelica