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.

export const MAX_INT_32 = 2 ** 31 - 1;

And then, on the id in the IdDto, use the @Max() validator with this value.

@Max(MAX_INT_32)

Commit - Validating id max value

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:

/^[a-zA-Z]+(?:\s[a-zA-Z]+)*$/

And the following error message:

'$property must contain only letters and spaces (no consecutive, leading or trailing)'

Finally, apply it on the field.

Commit - Validating user name as alphabetic with spaces

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.

Last updated