Custom validator
The next step is to tidy up the previous solution.
Not only the decorator above the password
field is pretty untidy, but also if you try to send a badly formatted password, the default error message reflects the regex, being hard to understand. In this section, we'll learn how to make our solution more elegant by using a Custom Validator.
Begin by creating the file common/decorators/validators/is-password.decorator with following content:
Let's not dwell too much on trying to understand everything of the code shown above too deeply. What is really important to notice is the isPassword()
function, which contains the logic to validate the password
. In this case, it is simply comparing the value
received against the regex through the matches()
function. And then, it is used in the IsPassword()
function, which is the actual decorator. There is mostly boilerplate inside it, we should notice however:
The
validate
field, which returns the validation functionThe
defaultMessage
, where we can customize the error message
Lastly, we can now use the @IsPassword()
decorator over the password
field.
Commit - Encapsulating password validation in custom validator
Last updated