Kest

Search

Search the documentation

Application

Validation

Constraint annotations, groups, your own constraints, and custom pipes.

Validation is class-validator and ValidationPipe. The processor writes a plain Kotlin validator for every class that uses a constraint (CreateUserDto_Validator), so nothing is reflective.

data class CreateUserDto(
    @NotBlank @Email val email: String,
    @Size(min = 8, max = 72) val password: String,
    @Valid val address: AddressDto? = null,
    @Valid val tags: List<TagDto> = emptyList(),
)
 
app.http(adapter) { usePipes(ValidationPipe::class) }        // import ValidationModule

A bad body is a 400 in the NestJS shape: {"statusCode":400,"message":["email must be an email","password must be between 8 and 72 characters long"],"error":"Bad Request"}.

Constraints

@NotBlank @NotEmpty @Email @Url @Uuid @Size @Min @Max @Positive @PositiveOrZero @Negative @NegativeOrZero @Pattern @OneOf @Valid. message = "..." replaces the text. @Valid checks a nested object or each element of a collection. Constraints on superclasses apply. null passes every constraint except @NotBlank and @NotEmpty, so a nullable type means "optional".

The pipe validates request bodies, and whole-object @Query and @Param bindings. For a single scalar argument write a Pipe.

Groups

The same class often has different rules on create and on update. Give constraints a group and choose the group per parameter:

interface Create : Default
interface Update : Default
 
data class AccountDto(
    @NotBlank(groups = [Create::class]) val id: String? = null,            // only when creating
    @NotBlank val name: String? = null,                                      // always (the Default group)
    @StrongPassword(groups = [Create::class]) val password: String? = null,
)
 
@Post fun create(@Validated(Create::class) @Body dto: AccountDto) = ...
@Put  fun update(@Validated(Update::class) @Body dto: AccountDto) = ...

A constraint with no group is in Default. Validating a group also validates the groups it extends, which is why Create : Default runs the unlabelled constraints too. Without @Validated only Default runs. In code: Validation.validate(dto, Create::class.java).

Your own constraints

An annotation marked @Constraint(validatedBy = ...) is a constraint like the built-in ones:

@Constraint(validatedBy = StrongPasswordValidator::class)
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.PROPERTY)
annotation class StrongPassword(val minLength: Int = 8, val message: String = "", val groups: Array<KClass<*>> = [])
 
class StrongPasswordValidator : ConstraintValidator {
    override fun isValid(value: Any?, context: ConstraintContext): Boolean {
        val s = value as? String ?: return true                          // null: other constraints decide
        if (s.length < context.int("minLength", 8)) { context.message("must be at least ${context.int("minLength", 8)} characters"); return false }
        if (s.none { it.isDigit() }) { context.message("must contain a digit"); return false }
        return true
    }
}

ConstraintContext gives the annotation's other members (context.int("minLength"), string, bool, or params), the property path, and the whole object as target, for rules across fields:

class MatchesPasswordValidator : ConstraintValidator {
    override fun isValid(value: Any?, context: ConstraintContext) = (context.target as SignupDto).password == value
}
@Constraint(validatedBy = MatchesPasswordValidator::class, name = "matchesPassword")
annotation class MatchesPassword(val message: String = "", val groups: Array<KClass<*>> = [])

context.message("...") sets the failure text (the property name is put in front). The validator needs a public no-argument constructor and is created once. Declare the annotation in the same Gradle module as the classes that use it.

Pipes

A pipe transforms or rejects a bound argument. It sees the value, and metadata: the kind (BODY, QUERY, PARAM, HEADER, COOKIE), the name, the type and the validation groups.

@Injectable
class TrimPipe : Pipe {
    override fun transform(value: Any?, meta: ArgumentMetadata): Any? =
        if (meta.kind == ParamKind.QUERY && value is String) value.trim() else value
}
 
@Injectable
class SlugPipe : Pipe {
    override fun transform(value: Any?, meta: ArgumentMetadata): Any? {
        if (meta.name != "slug") return value
        val s = value as String
        if (!Regex("[a-z0-9-]+").matches(s)) throw BadRequestException("slug must be lowercase letters, digits and dashes")
        return s
    }
}
 
app.http(adapter) { usePipes(TrimPipe::class, ValidationPipe::class) }       // global, in this order
@UsePipes(SlugPipe::class) @Get("/pages/{slug}") fun page(@Param slug: String) = ...       // one handler or controller

kest g pipe trim writes a skeleton. For the built-in conversions that NestJS does with ParseIntPipe, ParseUUIDPipe and DefaultValuePipe, the parameter's type and @Query(defaultValue = ...) do the work.

More string validators, messages and regular expressions

Every constraint takes message (your text) and groups:

data class SignUp(
    @NotBlank(message = "Tell us your name") @MinLength(2) @MaxLength(60) val name: String,
    @Email(message = "That is not an email address") val email: String,
    @Phone val phone: String?,                                   // +254 712 345 678, (415) 555-2671 ...
    @IpAddress(version = 4) val ip: String?,                     // 0 (default) accepts v4 and v6
    @Address(min = 5, max = 120) val address: String?,           // shape check: letters, a number, common punctuation
    @Pattern("^[A-Z]{2}-\\d{4}$", message = "Plate looks like KA-1234") val plate: String?,
    @StrongPassword(minLength = 10) val password: String,
)
ConstraintAccepts
@MinLength(n), @MaxLength(n)at least / at most n characters (or elements); @Size(min, max) does both
@Pattern(regex)the whole value matches the regular expression
@Email, @Url, @Uuid, @Hostname, @MacAddressthe format
@Phoneinternational phone numbers, 7 to 15 digits, with an optional + and common punctuation
@IpAddress(version)IPv4, IPv6 or either
@Address(min, max, requireNumber)a postal-address-shaped line; a shape check, not a lookup
@Alpha, @Alphanumeric, @Numeric, @Slugletters / letters and digits / digits / URL slug
@JsonString, @IsoDate, @CountryCode, @CreditCardvalid JSON / ISO-8601 date or date-time / ISO 3166 alpha-2 / Luhn-valid card number
@StrongPassword(...)length plus lower, upper, digit and symbol (each switchable)

null passes every constraint except @NotBlank and @NotEmpty, so an optional field is a nullable one.