Validation

Spark includes a powerful, automatic validation system based on annotations. You don't need to write manual checks for your data; just annotate your DTO fields, and Spark handles the rest.

How it Works

Validation is performed automatically when you use DTOs as the body type in your endpoints. For example, when you extend `SparkEndpointWithBody<YourDto>`, the framework will validate the DTO fields based on their validator annotations.

If validation fails, Spark automatically throws a `ValidationException`, which results in a 400 Bad Request response with a detailed JSON body explaining the errors.

Supported Validators

Spark provides a comprehensive set of validators for common use cases:

String Validators

  • `@NotEmpty([message])` - Checks that the string is not empty
  • `@Email([message])` - Checks that the string is a valid email address
  • `@Length({min, max, message})` - Checks string length is within range
  • `@Pattern(regex, [message])` - Checks string matches regular expression
  • `@IsString([message])` - Ensures the value is a string
  • `@IsBooleanString([message])` - Checks if string is "true", "false", "1", or "0"
  • `@IsDate([message])` - Checks if string is a valid ISO 8601 date
  • `@IsNumeric([message])` - Checks if string contains only numbers

Number Validators

  • `@Min(value, [message])` - Number must be greater than or equal to value
  • `@Max(value, [message])` - Number must be less than or equal to value

Example

Here is an example of a validated DTO:

class CreateUserDto {
  @NotEmpty(message: 'Username is required')
  @Length(min: 3, max: 20)
  final String username;

  @NotEmpty()
  @Email()
  final String email;

  @Min(18)
  final int age;

  CreateUserDto({
    required this.username,
    required this.email,
    required this.age,
  });

  // factory fromJson ...
}