Does scala suport JSR-303 validation?

前端 未结 2 1254
闹比i
闹比i 2021-01-06 16:40

Does scala supports JSR-303 validation?

If it does - could you please write an example?

If it does not - are there workarou

相关标签:
2条回答
  • 2021-01-06 17:41

    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.

    0 讨论(0)
  • 2021-01-06 17:44

    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.

    0 讨论(0)
提交回复
热议问题