Parameter validators
This page explains how to create ParameterValidators that perform checks against parameters after they are supplied by the user.
The ParameterValidator
interface is a part of the commands framework that allows you to perform custom validation on command parameters. This can be particularly useful when you want to enforce specific rules or constraints on command inputs, such as validating ranges, formats, or other criteria.
Implementing a Custom ParameterValidator
ParameterValidator
Let's create an example of a custom ParameterValidator
that checks if a number is within a specified range. This validator will make use of a custom annotation called @Range
to specify the minimum and maximum allowed values.
Step 1: Define the @Range
Annotation
@Range
AnnotationFirst, we'll create a custom annotation @Range
to specify the minimum and maximum values for our parameter:
Step 2: Implement the RangeValidator
RangeValidator
Next, we implement the RangeValidator
using the ParameterValidator
interface. This validator checks the parameter value against the @Range
annotation's constraints:
Step 3: Register the Validator
To use the RangeValidator
, you need to register it with your Lamp
instance. This is done through the Lamp.Builder
:
Step 4: Using the @Range
Annotation in Commands
@Range
Annotation in CommandsNow, you can use the @Range
annotation in your command methods to specify the valid range for numeric parameters:
In this example, the setAge
command requires the age
parameter to be between 18 and 99. If the user provides a value outside this range, the RangeValidator
will throw an exception, and Lamp will handle it appropriately.
Last updated
Was this helpful?