Update To Groovy Validator

I made a change to the Groovy Validator project.

I changed the names of the annotations. For example, “IntAnnotation” is now “ValidInt”. The same change was made for the other types.

Here is the new README file:

This project has a few annotations that validate fields in POGOs, sort of like Grails constraints.I will attempt to make some annotations for properties in Groovy.Here is a POGO:

It’s clean, and has no getters and setters. But what I do not like is there is no validation for your data. What if you want your String to be between 10 and 20 characters? What if you want your int field to be more than 100? And what’s to stop some dingo from trying to create a book object with less than 0 pages?

So I made some annotations that can do some validation for you.

For POGOs, if a numeric field is declared as “def”, it will become null if the argument does not meet the validation constraints. If it is declared as a primitive, it will be set to 0 if the argument does not meet the validation constraints.

This project can also validate fields in immutable objects. In addition to using the annotations for the fields, you annotate the class with ImmutableValidator:

To process the annotations, put your properties in a Map, and add a boolean called “validation” and set it to true (since I couldn’t overload the Map constructor, I added a boolean):

Adding the “throwEx” will throw an exception if the arguments do not meet the validation constraints. It is optional and is set to false by default. If an exception is thrown, it will print out the value and the constraints.

You might get a message like this:

You can also use it with immutable objects annotated with the ImmutableValidator annotation. This would be a second boolean after the Map with your properties, since the first boolean controls validation:

In that case, you get a message with a line for each field. So you might get a message like this:

If “throwException” is true for an immutable object and an exception is thrown, then the object will not be created.

This library can also handle final fields in mutable objects.

As with immutable validation, you need to use a map in the constructor to validate a final field.

Right now it only handles String, double, float, int and long. For String, it checks the string is checked against a minimum (“minLength”) and maximum (“maxLength”) length, and against a regular expression (“regEx”). For integers and longs, the field is checked against minimum (“minValue”) and maximum (“maxValue”) values, and a set of divisors (“divisorSet”). For double and float, the field is checked against minimum (“minValue”) and maximum (“maxValue”) values. There are defaults for all of these.

To use this project: Run

and use build/libs/groovy-validator.jar in your project.

You’re welcome.