开发者

How can i place validations for fields in groovy for specific format

开发者 https://www.devze.com 2023-03-05 10:36 出处:网络
I have Domain class and in that for a particular field of type String,开发者_Go百科 it accepts alphanumeric values,i need a validation in the format it should accept only AB12-QW-1 (or) XY-12 values.

I have Domain class and in that for a particular field of type String,开发者_Go百科 it accepts alphanumeric values,i need a validation in the format it should accept only AB12-QW-1 (or) XY-12 values. how can i validate the field.

Please suggest the solution. Thanks.


Assume your domain class looks like this

class Foo {
  String bar
}

If you can define a regex that matches only the legal values, you can apply the constraint using:

class Foo {
  String bar
  constraints = {
    bar(matches:"PUT-YOUR-REGEX-HERE")
  }
}

Alternatively, if you can easily list all the legal values, you can use:

class Foo {
  String bar
  constraints = {
    bar(inList:['AB12-QW-1', 'XY-12'])
  }
}

If neither of these solutions will work, then you'll likely need to write a custom validator method


You could use a custom validator:

class YourDomain {
  String code

  static constraints = {
    code( validator: {
      if( !( it in [ 'AB12-QW-1', 'XY-12' ] ) ) return ['invalid.code']
    })
  }
}

However, your explanation of what codes are valid is a bit vague, so you probably want something else in place of the in call

[edit]

Assuming your two strings just showed placeholders for letters or numbers, the following regexp validator should work:

constraints = {
  code( matches:'[A-Z]{2}[0-9]{2}-[A-Z]{2}-[0-9]|[A-Z]{2}-[0-9]{2}' )
}

And that will return the error yourDomain.code.matches.invalid if it fails

0

精彩评论

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