开发者

Validator for multiple types in grails

开发者 https://www.devze.com 2023-01-27 12:51 出处:网络
In a domain class I have a value from an enum which represents an email address or a URL class Contact{

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

精彩评论

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

关注公众号