Validation - S3nS3IW00/JCommands GitHub Wiki
InputArgument<I, O>
's input can be validated, and response can be set to every validation.
Validations in an argument stored in an ArgumentValidator<I>
that has a generic value I
that is the input type of the arugment. It can be accessed with InputArgument#getArgumentValidatior()
method. To add new validator ArgumentValidator#when(Predicate<T>)
or ArgumentValidator#when(ArugmentPredicate<T>)
has to be called. The difference between the methods is that the first one excpects a java Predicate<T>
, the second one expects an ArgumentPrediate<T>
that has various types. Both of the methods return an ArgumentValidation<T>
that stores the validation and provides the ArgumentValidation#thenRespond(ArgumentMismatchEventListener)
method that handle the response to the validation when the predicate is true
. Listener must be specified for every validation!
For example this validation limits the length of a String
input type argument, and triggers when the length is not between 8 and 16 (inclusively):
argument.getArgumentValidator().when(value -> value.length() < 8 || value.length() > 16)
.thenRespond(event -> {
event.getResponder().respondNow()
.setContent("Length must between 8 and 16!")
.respond();
});
Custom predicates that can be used to create more complex validations. Custom predicate can be created with implementing the ArgumentPredicate<T>
functional interface with the input type as generic parameter.
As its name shows this can be used to validate a String
input type argument by a regex pattern.
For example this argument accepts only numbers:
argument.getArgumentValidator().when(RegexPredicate.notValidFor("\\d+"))
.thenRespond(event -> {
event.getResponder().respondNow()
.setContent("Input is not a number!")
.respond();
});
This predicate contains methods to validate a String
input type argument by its length.
This predicate contains methods to validate a Long
input type argument.