More validations
Some more validations that may be interesting.
Id max value
The validation for the id
is nearly perfect. There is just one case where validation won't catch the problem: if the value is greater than the max value of the postgres integer (32-bit int). We can then create a constant for this value in common.constants.
And then, on the id
in the IdDto
, use the @Max()
validator with this value.
Commit - Validating max value of id
User name with only letters (and single spaces)
Currently, in the CreateUserDto
, the name
field should be a string with a certain length. However, anything can be passed. We can enforce that only letters are accepted. Unfortunately, we cannot use the @IsAlpha()
decorator from Class Validator, as it doesn't accept spaces. We must then create our own decorator that will accept spaces, and no consecutive/leading/trailing spaces. Do so in the same folder as the other text validators, and call it is-alpha-with-spaces.decorator. Please copy the contents of one of them, and then use the following for the regex:
And the following error message:
Finally, apply it on the field.
An alternative could be to have the fields firstName
and lastName
, and apply @IsAlpha()
over them, and even a locale
. In this case, we could also have the get field fullName
in the entity.
Commit - Validating user name as alphabetic with spaces
Last updated