Multiple validations

Better modularization of the password validation.

A limitation of our @IsPassword() validator, is that all the validations are being done in the same place. It would be nice to have a decorator for each individual validation. Then, the @IsPassword() would be a composition of all of them. The main advantage of this is that it would allow for a more detailed error message, stating what specific rule was not followed.

What we could do then is to create, inside the validators folder, the folder text-validation and inside it, five different decorators, one for each rule. So we could create the decorators:

  • AtLeastOneLowercaseLetter

  • AtLeastOneUppercaseLetter

  • AtLeastOneNumber

  • AtLeastOneSpecialCharacter

  • OnlyRequiredCharacters

So, begin by copying the contents of the is-password.decorator file and pasting them in the first decorator. I'll show you the steps to be taken and you can continue by yourself with the other ones. So, after pasting the contents, perform these steps:

  • Remove the JSDoc above the decorator

  • Rename everything accordingly, so what is called isPassword will become atLeastOneLowercaseLetter, for example

  • Adjust the error message to must contain at least one lowercase letter

  • Replace the regex with /.*[a-z].*/

After finishing this, copy the result to the remaining decorators and conclude adjusting them. The OnlyRequiredCharacters decorator has two differences:

  • Its regex should be /^[a-zA-Z\d@$!%*?&]+$/

  • The message should be must contain only letters, numbers and the following special characters: @$!%*?&

Finally, the @IsPassword() decorator should be a combination of all of them, and also the @Length() decorator with the required length for the password.

Commit - Separating password validation in multiple validations

Last updated