Does scala suport JSR-303 validation?
Asked Answered
C

2

5

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?

Cipher answered 18/6, 2014 at 11:40 Comment(1)
I've found Accord open-source library for validation.Nickles
H
7

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.

Hanging answered 18/6, 2014 at 17:23 Comment(3)
I wrote custom Constraint annotation in Java and ConstraintValidator in scala, but when I specify @Constraint(validatedBy = ScalaCustomerValidator.class) It gives compile error that Type mismatch: cannot convert from Class<ScalaCustomerValidator> to Class<? extends ConstraintValidator<?,?>>[]. My ScalaCustomerValidator does extends ConstraintValidatorBayless
@Hanging could you please provide the dependencies needed in order to use such annotations?Water
search.maven.org/artifact/javax.validation/validation-api/…Hanging
R
2

Sure!

However, custom annotations are needed for Scala types, as well as custom handling of collections.

If there is any interest, I'll opensource my implementation.

Ranite answered 16/8, 2019 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.