-
Notifications
You must be signed in to change notification settings - Fork 0
Validators
Validation in BetterYaml is the process of automatically correcting faulty configuration options. As of v1.1.0, our default validation options include:
- minimum values
- maximum values
- ranges (min & max)
- a set of allowed Strings
- automatic lowercasing
- Chaining any number of
Validators (mainly useful when adding your ownValidators) - An abstract Validator class that you can extend to create your own validator!
The best part? Faulty configuration options will automatically be fixed in the server admin's config files. On top of that, it is possible to create your own validators so you have full control over this process, we will get to this later.
This reduces the need to do any validation in your code and ensures correct values at all times.
Out story starts in the Validation class. Its constructor takes no arguments but we can use the builder pattern to create our own validator.
// Creates a new instance with no validation settings enabled
ValidationHandler validationHandler = new ValidationHandler();
// Add a validation method for one config path. Its value MUST be an integer and must be equal to, or larger than 12
validationHandler.addValidator("config_path", new Min(12));
// We can add more validators: eg. make an option always lowercase
validationHandler.addValidator("path_string", new LowerCase());
// The recommended approach to create such a validator, is using the builder pattern which achieves the same result:
ValidationHandler validation = new ValidationHandler()
.addValidator("config_path", new Min(12))
.addValidator("path_string", new LowerCase());
Once you have a ValidationHandler instance, it can be passed into any BetterYaml, OptionalBetterYaml or BetterLang constructor.
We'd like to direct you to our JavaDocs. The class hierarchy page contains a list of all Validator subclasses.
One special validation class stands out: ChainedValidator. By design, only one validator is allowed per path. When more validators are required for a single path, ChainedValidator allows you to chain multiple different validators. It's constructor takes any amount of arguments, where every argument is a Validator.
To create your own, custom Validator, simply create a class that extends Validator and enable it as you would do for any of our default Validators. A simple example is shown below. It ensures that a value is always a String and will return one in all lowercase.
public class ToLowerCase extends Validator
{
/**
* Makes any validated input lowercase
* Any non-String will be converted to an empty String
*/
public ToLowerCase() {}
@Override
public Object validate(@NotNull Object o)
{
if ( !(o instanceof String) )
return "";
String str = (String) o;
return str.toLowerCase();
}
}
Please use OptionalBetterYaml instead.
Auto-correct faulty configuration values! You can create your own, custom validators.