Regular Expressions in Groovy Validator

There is another update to the Groovy Validator project. I added regular expressions to the StringAnnotation class. I have not added it to the class that performs validation for immutable objects.

Before, all you could do is validate a String by length. Now you can also use regular expressions:


class ImmutableRegEx {
    @StringAnnotation( minLength = 10, regEx = /^.*?[Gg]roovy.*$/ ) 
    String groovyString
    @StringAnnotation( regEx = /\d{4}?-\d\d-\d\d/  ) 
    String yearWithDay
    @StringAnnotation( minLength = 6, maxLength = 10, regEx = /^(?=.*[0-9].*[0-9])[0-9a-zA-Z]{8,12}$/ )
    String password

The default is the catch-all “.*”, so the annotation will still work with no regular expression provided by the user. This can be used with POGOs and processed by AnnotationProcessor.process, and it can be used with ImmutableValidator. If you are going to use regular expressions with ImmutableValidator, you must delimit the regex string with slashes. If you are using regular expressions with AnnotationProcessor, you can delimit the regex string with slashes or quotes. But, as always, if you use quotes, you have to do a lot of escaping yourself.

The regular expression has to be unbroken on one line. This means you cannot use comments to document them.

I also beefed up the annotation AST transformer for immutable objects. I put annotations on every field in the immutable objects I was testing, and it was only now that I realized that it choked on a field in an immutable object that did not have any validation annotation. I think I fixed that.

I keep thinking I am done, but I have one more change I think I can make.

You’re welcome.

There are 272 words in this article.