CLI2 provides a mechanism to validate argument values. The Validator interface must be implemented to create an argument validator. This interface has a single method validate(java.util.List values) throws InvalidArgumentException.
CLI2 has some standard validators included. They validate the following:
The ClassValidator validates a value using three criteria:
// 1. ClassValidator validator = new ClassValidator(); // 2. validator.setLoadable(true); // 3. validator.setLoadable(true);
TODO: add section about values being replaced with class instances
The DateValidator validates values against a java.text.DateFormat. There are three helper methods that create built-in validators.
A DateValidator can also be created by passing your a custom DateFormat into the constructor.
DateFormat myFormat = DateFormat.getDateInstance( DateFormat.LONG, Locale.UK ); DateValidator myValidator = new DateValidator( myFormat );
In addition to basic format checking you can also check if the date/time specified is before/after a specific date/time. The lower bound is set using the setMinimum( java.util.Date ), and the upper bound is set using the setMaximum( java.util.Date ).
TODO: add section about values being replaced with date instances
The EnumValidator validates values against a list of allowed string values. The values that are allowed are specified in a java.util.Set and passed in to the constructor.
Set enumSet = new TreeSet(); enumSet.add("red"); enumSet.add("green"); enumSet.add("blue"); EnumValidator validator = new EnumValidator( enumSet );
The FileValidator validates that values represent existing files. You can also specify a combination of the following additional criteria:
Each of the criteria listed here are specified using the appropriate setter.
There are three helper methods to create validators:
// validate that the value represents a file that exists FileValidator validator = FileValidator.getExistingInstance(); // ensure it's not a hidden file validator.setHidden( false ); // ensure it's a writable file validator.setWritable( true );
The NumberValidator validates that values adhere to certain rules like the following:
A NumberValidator can also be created by passing your a custom NumberFormat into the constructor.
NumberFormat myFormat = NumberFormat.getCurrencyInstance( Locale.UK ); NumberValidator myValidator = new NumberValidator( myFormat );
In addition to basic format checking you can also check if the number specified is less than or greater than a specific number. The lower bound is set using the setMinimum( Number ), and the upper bound is set using the setMaximum( Number ).