Using 'class-validator' to Validate Arguments
By default Discapp does basic command validation. For example:
- Ensures that mention arguments are mention
- Ensure that numeric arguments are numbers
- Ensure that required arguments are given
But doing more complex validations are not the Discapp scope, since already exists lots of excelent libaries for validating data.
Discapp recommend you to use class-validator
library for validating your arguments, as the syntax fits pretty well.
In this chapter you will learn how to integrate Discapp and class-validator.
class-validator
#
Installing class-validator is not insalled by default in Discapp. You can install it by executing:
BaseCommand
#
Supercharging the Every command has to extends from BaseCommand, but not directly from it.
In this chapter we will write the abstract class EnhancedCommand
that will extend from BaseCommand
and add extra functionality to it.
The code bellow does the following:
- Validates the arguments.
- If they're not correct throw, so the
execute
method is not invoked. - Re-throws the error as a
BadInputException
so Discapp can warn the user about his error.
#
Validating Your ClassesLet's rewrite the GreetCommand.ts
so it only accept names with 4 characters or more:
note
The MinLength
decorator is coming from class-validator
.
Now if you try sending:
You should see something like this, as Ava is only 3 characters long:
You can also compose multiple validations.
Let's you don't allow your command to greet persons with the name 'Adam':
Now if you try to greet Adam by sending:
You should see: