开发者

Validator for multiple types in grails

In a domain class I have a value from an enum which represents an email address or a URL

class Contact{
  ContactType contact
  String value
}

enum ContactType{
  EMAIL,
  URL
}

I'm trying to use the built in grails EmailConstraint and UrlConstraint classes to validate:

stati开发者_运维技巧c constraints = {
  value(validator: {
    ContactType.validate(obj, val, errors)
  })
}

I managed to make it work by making some assumptions reading grails source:

Constraint constraint = new EmailConstraint()
constraint.setPropertyName "value"
constraint.setOwningClass obj.class
constraint.setParameter true
constraint.validate(obj, obj.value, errors)

But I find this very ugly, so I was wondering if anyone can offer a better solution.

Thanks.


You might implement a custom constraint for this case using http://www.grails.org/plugin/constraints. The new constraint class might delegate internally to EmailConstraint or to a kind of "URLConstraint" depending on the enum value.

Using this approach, your domain class stays clean an small, validation details are seperated into a different class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜