开发者

Add constraints to properties of Groovy class (not Grails domain class!)

How can we add some common constraints (i.e. maxLength, nullable) to a property of a Groovy class? I know we can do it at Grails domain class, but is it possible if that is a Groovy class (I use it as a DTO class for my Grails project)?

Thank you so mu开发者_C百科ch!


You can add constraints to command classes. If a command class is in the same .groovy file as a controller (in Groovy you can have more than one public class in each .groovy file), you don't need to do anything special for Grails to recongise it as a command class.

However, if your command class is somewhere else (e.g. under src/groovy), you need to annotate it with @Validateable and add the package name to the grails.validateable.packages parameter in Config.groovy. Here's an example of a command that's not in the same file as a controller

pacakge com.example.command

@Validateable
class Person {
  Integer age
  String name

  static constraints = {
    name(blank: false)
    age(size 0..100)
  }
}

Add the following to Config.groovy

grails.validateable.packages = ['com.example.command']

Command classes have a validate() method added by Grails. After this method is called, any errors will be available in the errors property (as per domain classes).


Using a grails Command Object is probably your best bet. It has constraints and validation, but no database backing. It's normally a value object that controllers use, but you could instantiate one outside of a controller without any problems.


Not sure if this is relevant to your use (I am not familiar with DTOs), but in the current version (2.3.8), you can also add Grails constraints to an abstract class, and they will be inherited by the domains that extend it. Your IDE might not like it though ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜