srini
srini

Reputation: 6959

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

I have Domain class and in that for a particular field of type String, 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.

Upvotes: 1

Views: 867

Answers (2)

Dónal
Dónal

Reputation: 187519

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

Upvotes: 3

tim_yates
tim_yates

Reputation: 171084

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

Upvotes: 1

Related Questions