Validator Decorations
Validator Decorations are native validation annotations for tyrus. They can be attached to interface fields, object type fields and function parameters. The compiler checks that each validator exists, targets a compatible type and receives literal arguments of the expected kind.
Example
interface UserInput {
@minLength(3)
@maxLength(32)
name: string;
@email()
primaryEmail: string;
@min(18, "The minimum age requirement is 18")
age: u8;
}
const divide = (a: f64, @notEqual(0) b: f64): f64 => a / b;Built-in validators check literal values at compile time and run at runtime for dynamic values in decorated parameters, object literals and object updates.
Validator Decorations in .env Files
Tyrus accepts Validator Decorations in .env files with or without a leading #. Use the commented form when another .env loader, such as Docker, also reads the file; Tyrus still parses the decoration while other loaders see a comment.
# @type(u16)
# @port()
PORT=8080Error Messages
Built-in validators let you override their default message with a string literal as the last argument they accept.
interface SignupInput {
@minLength(3)
username: string;
@minLength(8, "password must have at least 8 characters")
password: string;
@email("use a valid company e-mail")
email: string;
}The same rule works on decorated function parameters.
const divide = (value: f64, @notEqual(0, "division by zero is not allowed") divisor: f64): f64 => {
return value / divisor;
};Prefer user-facing custom messages at boundaries
Default messages are useful during development. Custom messages are better for API boundaries, CLI prompts, and validation failures that may be shown to users.
Validator Families
| Family | Examples |
|---|---|
| Numeric | @min, @max, @range, @positive, @negative, @nonNegative, @nonPositive, @multipleOf, @powerOfTwo, @integer, @safeInteger, @port, @statusCode |
| String | @minLength, @maxLength, @length, @notEmpty, @notBlank, @isTrimmed, @isLowercase, @isUppercase, @startsWith, @endsWith, @includes, @regex |
| Format | @email, @url, @uuid, @ip, @ipv4, @ipv6, @e164, @cep, @cpf, @cnpj |
| Arrays and values | @minItems, @maxItems, @lengthItems, @notEmptyItems, @unique, @in, @notIn, @equal, @notEqual, @notNull, @optional, @required |
Validator Targets
A numeric validator is checked in the arithmetic of the type it decorates: an i64 field is compared as an integer and an f64 field as a float. A whole number past 2^53 therefore keeps its exact value, and the compile-time verdict always agrees with the check emitted for the same value.
@port, @powerOfTwo, and @statusCode target integer types only, because their rules have no reading on a fractional value. A port is not 8080.5.
@unique compares elements by value, so it accepts arrays of numbers, strings, booleans, enums, tuples, object types, and named interfaces whose fields are themselves compared by value. An array of arrays is rejected at compile time: arrays are compared by address, so [[1, 2], [1, 2]] would be reported as unique.
Validator Operation
Each validator family enforces specific constraints on the values it decorates. The compiler checks literal values at compile time and emits runtime checks for dynamic values. Below are examples for every validator family with their default error messages.
Numeric
@min
Enforces that the value is at least the specified minimum.
@min(value: i8 | i16 | i32 | i64 | u8 | u16 | u32 | u64 | f32 | f64 | f128, message?: string)interface Example {
@min(1)
pageSize: u32;
}
const valid: Example = { pageSize: 5 };error
const invalid: Example = { pageSize: 0 }; error[validator-decorations-failed]: `@min(1)` failed for `pageSize`: value must be greater than or equal to 1
at /src/main.tyr:6:38
const invalid: Example = { pageSize: 0 };
^@max
Enforces that the value is at most the specified maximum.
@max(value: i8 | i16 | i32 | i64 | u8 | u16 | u32 | u64 | f32 | f64 | f128, message?: string)interface Example {
@max(100)
limit: i32;
}
const valid: Example = { limit: 50 };error
const invalid: Example = { limit: 200 }; error[validator-decorations-failed]: `@max(100)` failed for `limit`: value must be less than or equal to 100
at /src/main.tyr:6:35
const invalid: Example = { limit: 200 };
^^^@range
Enforces that the value falls within the specified inclusive range.
@range(min: i8 | i16 | i32 | i64 | u8 | u16 | u32 | u64 | f32 | f64 | f128, max: i8 | i16 | i32 | i64 | u8 | u16 | u32 | u64 | f32 | f64 | f128, message?: string)interface Example {
@range(1, 50)
offset: i32;
}
const valid: Example = { offset: 25 };error
const invalid: Example = { offset: 60 }; error[validator-decorations-failed]: `@range(1, 50)` failed for `offset`: value must be between 1 and 50
at /src/main.tyr:6:36
const invalid: Example = { offset: 60 };
^^@positive
Enforces that the value is greater than zero.
@positive(message?: string)interface Example {
@positive()
amount: f64;
}
const valid: Example = { amount: 5.0 };error
const invalid: Example = { amount: -5.0 }; error[validator-decorations-failed]: `@positive()` failed for `amount`: value must be positive
at /src/main.tyr:6:36
const invalid: Example = { amount: -5.0 };
^^^^@negative
Enforces that the value is less than zero.
@negative(message?: string)interface Example {
@negative()
debt: f64;
}
const valid: Example = { debt: -10.0 };error
const invalid: Example = { debt: 10.0 }; error[validator-decorations-failed]: `@negative()` failed for `debt`: value must be negative
at /src/main.tyr:6:34
const invalid: Example = { debt: 10.0 };
^^^^@nonNegative
Enforces that the value is zero or greater.
@nonNegative(message?: string)interface Example {
@nonNegative()
balance: f64;
}
const valid: Example = { balance: 0.0 };error
const invalid: Example = { balance: -1.0 }; error[validator-decorations-failed]: `@nonNegative()` failed for `balance`: value must be non-negative
at /src/main.tyr:6:37
const invalid: Example = { balance: -1.0 };
^^^^@nonPositive
Enforces that the value is zero or less.
@nonPositive(message?: string)interface Example {
@nonPositive()
withdrawal: f64;
}
const valid: Example = { withdrawal: 0.0 };error
const invalid: Example = { withdrawal: 5.0 }; error[validator-decorations-failed]: `@nonPositive()` failed for `withdrawal`: value must be non-positive
at /src/main.tyr:6:40
const invalid: Example = { withdrawal: 5.0 };
^^^@multipleOf
Enforces that the value is a multiple of the given divisor.
@multipleOf(value: i8 | i16 | i32 | i64 | u8 | u16 | u32 | u64 | f32 | f64 | f128, message?: string)interface Example {
@multipleOf(5)
quantity: i32;
}
const valid: Example = { quantity: 10 };error
const invalid: Example = { quantity: 7 }; error[validator-decorations-failed]: `@multipleOf(5)` failed for `quantity`: value must be a multiple of 5
at /src/main.tyr:6:38
const invalid: Example = { quantity: 7 };
^@powerOfTwo
Enforces that the value is a power of two.
@powerOfTwo(message?: string)interface Example {
@powerOfTwo()
bufferSize: u32;
}
const valid: Example = { bufferSize: 8 };error
const invalid: Example = { bufferSize: 3 }; error[validator-decorations-failed]: `@powerOfTwo()` failed for `bufferSize`: value must be a power of two
at /src/main.tyr:6:40
const invalid: Example = { bufferSize: 3 };
^@integer
Enforces that a floating-point value has no fractional part.
@integer(message?: string)interface Example {
@integer()
count: f64;
}
const valid: Example = { count: 42.0 };error
const invalid: Example = { count: 3.14 }; error[validator-decorations-failed]: `@integer()` failed for `count`: value must be an integer
at /src/main.tyr:6:35
const invalid: Example = { count: 3.14 };
^^^^@safeInteger
Enforces that the integer value is within the safe integer range ±2⁵³.
@safeInteger(message?: string)interface Example {
@safeInteger()
largeId: f64;
}
const valid: Example = { largeId: 9007199254740992 };error
const invalid: Example = { largeId: 9007199254740993 }; error[E0308]: type mismatch for `largeId`: expected `f64`, found `9007199254740993`
at /src/main.tyr:6:28
const invalid: Example = { largeId: 9007199254740993 };
^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`@port
Enforces that the value is a registered port number between 1024 and 49151.
@port(message?: string)interface Example {
@port()
serverPort: u16;
}
const valid: Example = { serverPort: 8080 };error
const invalid: Example = { serverPort: 80 }; error[validator-decorations-failed]: `@port()` failed for `serverPort`: value must be a registered port between 1024 and 49151
at /src/main.tyr:6:40
const invalid: Example = { serverPort: 80 };
^^@statusCode
Enforces that the value is a valid HTTP status code between 100 and 599.
@statusCode(message?: string)interface Example {
@statusCode()
responseCode: u16;
}
const valid: Example = { responseCode: 200 };error
const invalid: Example = { responseCode: 99 }; error[validator-decorations-failed]: `@statusCode()` failed for `responseCode`: value must be a valid HTTP status code between 100 and 599
at /src/main.tyr:6:42
const invalid: Example = { responseCode: 99 };
^^String
@minLength
Enforces that the string contains at least the specified number of characters.
@minLength(value: i64, message?: string)interface Example {
@minLength(3)
username: string;
}
const valid: Example = { username: "abc" };error
const invalid: Example = { username: "ab" }; error[validator-decorations-failed]: `@minLength(3)` failed for `username`: value must contain at least 3 characters
at /src/main.tyr:6:38
const invalid: Example = { username: "ab" };
^^^^@maxLength
Enforces that the string contains at most the specified number of characters.
@maxLength(value: i64, message?: string)interface Example {
@maxLength(50)
displayName: string;
}
const valid: Example = { displayName: "A".repeat(10) };error
const invalid: Example = { displayName: "A".repeat(51) }; error[unhandled-throw]: validation of field `displayName` may throw `ValidationError`; catch it or add `throws ValidationError` to the enclosing function
at /src/main.tyr:6:41
const invalid: Example = { displayName: "A".repeat(51) };
^^^^^^^^^^^^^^@length
Enforces that the string has exactly the specified length.
@length(value: i64, message?: string)interface Example {
@length(8)
code: string;
}
const valid: Example = { code: "12345678" };error
const invalid: Example = { code: "1234567" }; error[validator-decorations-failed]: `@length(8)` failed for `code`: value must have exactly 8 characters
at /src/main.tyr:6:34
const invalid: Example = { code: "1234567" };
^^^^^^^^^@notEmpty
Enforces that the string is not empty.
@notEmpty(message?: string)interface Example {
@notEmpty()
firstName: string;
}
const valid: Example = { firstName: "John" };error
const invalid: Example = { firstName: "" }; error[validator-decorations-failed]: `@notEmpty()` failed for `firstName`: value must not be empty
at /src/main.tyr:6:39
const invalid: Example = { firstName: "" };
^^@notBlank
Enforces that the string contains at least one non-whitespace character.
@notBlank(message?: string)interface Example {
@notBlank()
bio: string;
}
const valid: Example = { bio: "Hello" };error
const invalid: Example = { bio: " " }; error[validator-decorations-failed]: `@notBlank()` failed for `bio`: value must not be blank
at /src/main.tyr:6:33
const invalid: Example = { bio: " " };
^^^^^@isTrimmed
Enforces that the string has no leading or trailing whitespace.
@isTrimmed(message?: string)interface Example {
@isTrimmed()
title: string;
}
const valid: Example = { title: "no spaces" };error
const invalid: Example = { title: " spaces " }; error[validator-decorations-failed]: `@isTrimmed()` failed for `title`: value must already be trimmed
at /src/main.tyr:6:35
const invalid: Example = { title: " spaces " };
^^^^^^^^^^@isLowercase
Enforces that the string contains only lowercase characters.
@isLowercase(message?: string)interface Example {
@isLowercase()
slug: string;
}
const valid: Example = { slug: "valid-slug" };error
const invalid: Example = { slug: "Invalid-Slug" }; error[validator-decorations-failed]: `@isLowercase()` failed for `slug`: value must already be lowercase
at /src/main.tyr:6:34
const invalid: Example = { slug: "Invalid-Slug" };
^^^^^^^^^^^^^^@isUppercase
Enforces that the string contains only uppercase characters.
@isUppercase(message?: string)interface Example {
@isUppercase()
countryCode: string;
}
const valid: Example = { countryCode: "BR" };error
const invalid: Example = { countryCode: "br" }; error[validator-decorations-failed]: `@isUppercase()` failed for `countryCode`: value must already be uppercase
at /src/main.tyr:6:41
const invalid: Example = { countryCode: "br" };
^^^^@startsWith
Enforces that the string begins with the given prefix.
@startsWith(value: string, message?: string)interface Example {
@startsWith("user_")
userId: string;
}
const valid: Example = { userId: "user_abc" };error
const invalid: Example = { userId: "abc_123" }; error[validator-decorations-failed]: `@startsWith("user_")` failed for `userId`: value must start with "user_"
at /src/main.tyr:6:36
const invalid: Example = { userId: "abc_123" };
^^^^^^^^^@endsWith
Enforces that the string ends with the given suffix.
@endsWith(value: string, message?: string)interface Example {
@endsWith(".md")
fileName: string;
}
const valid: Example = { fileName: "readme.md" };error
const invalid: Example = { fileName: "readme.txt" }; error[validator-decorations-failed]: `@endsWith(".md")` failed for `fileName`: value must end with ".md"
at /src/main.tyr:6:38
const invalid: Example = { fileName: "readme.txt" };
^^^^^^^^^^^^@includes
Enforces that the string contains the given substring.
@includes(value: string, message?: string)interface Example {
@includes("@")
handle: string;
}
const valid: Example = { handle: "user@domain" };error
const invalid: Example = { handle: "no-at-sign" }; error[validator-decorations-failed]: `@includes("@")` failed for `handle`: value must include "@"
at /src/main.tyr:6:36
const invalid: Example = { handle: "no-at-sign" };
^^^^^^^^^^^^@regex
Enforces that the string matches the given regular expression.
@regex(value: Regex, message?: string)interface Example {
@regex(/^[a-z]+$/)
alphaName: string;
}
const valid: Example = { alphaName: "hello" };error
const invalid: Example = { alphaName: "user123" }; error[validator-decorations-failed]: `@regex(/^[a-z]+$/)` failed for `alphaName`: value must match /^[a-z]+$/
at /src/main.tyr:6:39
const invalid: Example = { alphaName: "user123" };
^^^^^^^^^Format
@email
Enforces that the value is a valid e-mail address.
@email(message?: string)interface Example {
@email()
contactEmail: string;
}
const valid: Example = { contactEmail: "[email protected]" };error
const invalid: Example = { contactEmail: "not-an-email" }; error[validator-decorations-failed]: `@email()` failed for `contactEmail`: value must be a valid e-mail address
at /src/main.tyr:6:42
const invalid: Example = { contactEmail: "not-an-email" };
^^^^^^^^^^^^^^@url
Enforces that the value is a valid URL.
@url(message?: string)interface Example {
@url()
website: string;
}
const valid: Example = { website: "https://example.com" };error
const invalid: Example = { website: "not-a-url" }; error[validator-decorations-failed]: `@url()` failed for `website`: value must be a valid URL
at /src/main.tyr:6:37
const invalid: Example = { website: "not-a-url" };
^^^^^^^^^^^@uuid
Enforces that the value is a valid UUID.
@uuid(message?: string)interface Example {
@uuid()
sessionId: string;
}
const valid: Example = { sessionId: "550e8400-e29b-41d4-a716-446655440000" };error
const invalid: Example = { sessionId: "not-a-uuid" }; error[validator-decorations-failed]: `@uuid()` failed for `sessionId`: value must be a valid UUID
at /src/main.tyr:6:39
const invalid: Example = { sessionId: "not-a-uuid" };
^^^^^^^^^^^^@ip
Enforces that the value is a valid IP address (v4 or v6).
@ip(message?: string)interface Example {
@ip()
clientIp: string;
}
const valid: Example = { clientIp: "192.168.1.1" };error
const invalid: Example = { clientIp: "999.999.999.999" }; error[validator-decorations-failed]: `@ip()` failed for `clientIp`: value must be a valid IP address
at /src/main.tyr:6:38
const invalid: Example = { clientIp: "999.999.999.999" };
^^^^^^^^^^^^^^^^^@ipv4
Enforces that the value is a valid IPv4 address.
@ipv4(message?: string)interface Example {
@ipv4()
localhost: string;
}
const valid: Example = { localhost: "127.0.0.1" };error
const invalid: Example = { localhost: "999.999.999.999" }; error[validator-decorations-failed]: `@ipv4()` failed for `localhost`: value must be a valid IPv4 address
at /src/main.tyr:6:39
const invalid: Example = { localhost: "999.999.999.999" };
^^^^^^^^^^^^^^^^^@ipv6
Enforces that the value is a valid IPv6 address.
@ipv6(message?: string)interface Example {
@ipv6()
ipv6Host: string;
}
const valid: Example = { ipv6Host: "::1" };error
const invalid: Example = { ipv6Host: "not-ipv6" }; error[validator-decorations-failed]: `@ipv6()` failed for `ipv6Host`: value must be a valid IPv6 address
at /src/main.tyr:6:38
const invalid: Example = { ipv6Host: "not-ipv6" };
^^^^^^^^^^@e164
Enforces that the value is a valid E.164 phone number.
@e164(message?: string)interface Example {
@e164()
phoneNumber: string;
}
const valid: Example = { phoneNumber: "+5511999999999" };error
const invalid: Example = { phoneNumber: "1234567890" }; error[validator-decorations-failed]: `@e164()` failed for `phoneNumber`: value must be a valid E.164 phone number
at /src/main.tyr:6:41
const invalid: Example = { phoneNumber: "1234567890" };
^^^^^^^^^^^^@cep
Enforces that the value is a valid Brazilian postal code (CEP).
@cep(message?: string)interface Example {
@cep()
postalCode: string;
}
const valid: Example = { postalCode: "01310-100" };error
const invalid: Example = { postalCode: "12345" }; error[validator-decorations-failed]: `@cep()` failed for `postalCode`: value must be a valid Brazilian postal code
at /src/main.tyr:6:40
const invalid: Example = { postalCode: "12345" };
^^^^^^^@cpf
Enforces that the value is a valid Brazilian CPF.
@cpf(message?: string)interface Example {
@cpf()
taxId: string;
}
const valid: Example = { taxId: "529.982.247-25" };error
const invalid: Example = { taxId: "12345678901" }; error[validator-decorations-failed]: `@cpf()` failed for `taxId`: value must be a valid Brazilian CPF
at /src/main.tyr:6:35
const invalid: Example = { taxId: "12345678901" };
^^^^^^^^^^^^^@cnpj
Enforces that the value is a valid Brazilian CNPJ.
@cnpj(message?: string)interface Example {
@cnpj()
companyTaxId: string;
}
const valid: Example = { companyTaxId: "11.444.777/0001-61" };error
const invalid: Example = { companyTaxId: "12345678901234" }; error[validator-decorations-failed]: `@cnpj()` failed for `companyTaxId`: value must be a valid Brazilian CNPJ
at /src/main.tyr:6:42
const invalid: Example = { companyTaxId: "12345678901234" };
^^^^^^^^^^^^^^^^Array
@minItems
Enforces that the array contains at least the specified number of items.
@minItems(value: i64, message?: string)interface Example {
@minItems(1)
tags: string[];
}
const valid: Example = { tags: ["hello"] };error
const invalid: Example = { tags: [] }; error[validator-decorations-failed]: `@minItems(1)` failed for `tags`: array must contain at least 1 items
at /src/main.tyr:6:34
const invalid: Example = { tags: [] };
^^@maxItems
Enforces that the array contains at most the specified number of items.
@maxItems(value: i64, message?: string)interface Example {
@maxItems(10)
selectedIds: i32[];
}
const valid: Example = { selectedIds: [1, 2, 3] };error
const invalid: Example = { selectedIds: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] }; error[validator-decorations-failed]: `@maxItems(10)` failed for `selectedIds`: array must contain at most 10 items
at /src/main.tyr:6:41
const invalid: Example = { selectedIds: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] };
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^@lengthItems
Enforces that the array has exactly the specified length.
@lengthItems(value: i64, message?: string)interface Example {
@lengthItems(3)
coordinates: f64[];
}
const valid: Example = { coordinates: [1.0, 2.0, 3.0] };error
const invalid: Example = { coordinates: [1.0, 2.0] }; error[validator-decorations-failed]: `@lengthItems(3)` failed for `coordinates`: array must contain exactly 3 items
at /src/main.tyr:6:41
const invalid: Example = { coordinates: [1.0, 2.0] };
^^^^^^^^^^@notEmptyItems
Enforces that the array is not empty.
@notEmptyItems(message?: string)interface Example {
@notEmptyItems()
members: string[];
}
const valid: Example = { members: ["user1"] };error
const invalid: Example = { members: [] }; error[validator-decorations-failed]: `@notEmptyItems()` failed for `members`: array must not be empty
at /src/main.tyr:6:37
const invalid: Example = { members: [] };
^^@unique
Enforces that all items in the array are distinct.
@unique(message?: string)interface Example {
@unique()
permissions: string[];
}
const valid: Example = { permissions: ["read", "write"] };error
const invalid: Example = { permissions: ["read", "write", "read"] }; error[validator-decorations-failed]: `@unique()` failed for `permissions`: array items must be unique
at /src/main.tyr:6:41
const invalid: Example = { permissions: ["read", "write", "read"] };
^^^^^^^^^^^^^^^^^^^^^^^^^Equality and membership
@equal
Enforces that the value equals the given literal.
@equal(value: T, message?: string)interface Example {
@equal("active")
status: string;
}
const valid: Example = { status: "active" };error
const invalid: Example = { status: "inactive" }; error[validator-decorations-failed]: `@equal("active")` failed for `status`: value must be equal to "active"
at /src/main.tyr:6:36
const invalid: Example = { status: "inactive" };
^^^^^^^^^^@notEqual
Enforces that the value differs from the given literal.
@notEqual(value: T, message?: string)interface Example {
@notEqual("deleted")
accountType: string;
}
const valid: Example = { accountType: "active" };error
const invalid: Example = { accountType: "deleted" }; error[validator-decorations-failed]: `@notEqual("deleted")` failed for `accountType`: value must be different from "deleted"
at /src/main.tyr:6:41
const invalid: Example = { accountType: "deleted" };
^^^^^^^^^@in
Enforces that the value is one of the specified options.
@in(value: T[], message?: string)interface Example {
@in(["red", "green", "blue"])
color: string;
}
const valid: Example = { color: "blue" };error
const invalid: Example = { color: "yellow" }; error[validator-decorations-failed]: `@in(["red", "green", "blue"])` failed for `color`: value must be one of ["red", "green", "blue"]
at /src/main.tyr:6:35
const invalid: Example = { color: "yellow" };
^^^^^^^^@notIn
Enforces that the value is not one of the specified options.
@notIn(value: T[], message?: string)interface Example {
@notIn(["admin", "superadmin"])
role: string;
}
const valid: Example = { role: "user" };error
const invalid: Example = { role: "admin" }; error[validator-decorations-failed]: `@notIn(["admin", "superadmin"])` failed for `role`: value must not be one of ["admin", "superadmin"]
at /src/main.tyr:6:34
const invalid: Example = { role: "admin" };
^^^^^^^Nullability and presence
@notNull
Enforces that an optional target carries a value.
@notNull(message?: string)interface Example {
@notNull()
requiredField: string?;
}
const valid: Example = { requiredField: "hello" };error
const invalid: Example = { requiredField: null }; error[unhandled-throw]: validation of field `requiredField` may throw `ValidationError`; catch it or add `throws ValidationError` to the enclosing function
at /src/main.tyr:6:43
const invalid: Example = { requiredField: null };
^^^^
error[validator-decorations-failed]: `@notNull()` failed for `requiredField`: value must not be null
at /src/main.tyr:6:43
const invalid: Example = { requiredField: null };
^^^^
error[E0308]: type mismatch for `requiredField`: expected `string?`, found `null`
at /src/main.tyr:6:28
const invalid: Example = { requiredField: null };
^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`@optional
Marks a field or parameter as explicitly optional.
@optional(message?: string)interface Example {
@optional()
nickName: string?;
}
const validWithValue: Example = { nickName: "Johnny" };
const validAbsent: Example = {};@required
Enforces that the target has a value.
@required(message?: string)interface Example {
@required()
mandatoryParam: string;
}
const valid: Example = { mandatoryParam: "present" };error
const invalid: Example = { /* missing mandatoryParam */ }; error[E2741]: property `mandatoryParam` is missing in object literal for type `Example`
at /src/main.tyr:6:7
const invalid: Example = { /* missing mandatoryParam */ };
^^^^^^^Validation is applied automatically when typed objects are created or updated and when decorated functions are called. Route-schema behavior belongs to the HTTP roadmap and is not part of this language-level mechanism.
Optional Targets
A validator placed on an optional target applies to the value the optional carries, so it only runs when a value is present. An absent optional passes every validator except @notNull and @required, which test presence itself and therefore apply to the optional rather than to its payload.
interface Contact {
@email()
email?: string;
}
const acceptAge = (@min(18) age?: i32): void => {
print(age ?? -1); // -1
};
const main = (): void => {
const empty: Contact = {};
print(empty.email ?? "no e-mail"); // "no e-mail"
try {
acceptAge();
} catch (error: ValidationError) {
print(error.issues[0].validator); // "min"
}
};Neither the omitted email field nor the omitted age argument fails validation: there is no value to check. Supplying an invalid value makes the same validators fail exactly as they would on a required target.
Recoverable Runtime Validation
Dynamic validation failures throw ValidationError; they do not stop the application when handled. ValidationError.issues is always present and contains at least one read-only ValidationIssue, so the same handling works whether one rule or several rules fail. A decorated function implicitly declares this effect. An intermediate function must catch it or propagate it with throws ValidationError, while main must handle every reachable error and cannot declare throws.
Each issue target is a deterministic logical path. Nested fields use dot notation such as profile.address.zipCode, and array elements include their zero-based index such as members[0].address.zipCode.
The path is rooted at the value the operation validates, not at some outermost type. Building a nested object into its own variable first makes that construction a validation operation of its own, so its issues are rooted there: the target is zipCode, not members[0].address.zipCode.
One validation operation collects every failed rule before throwing: an object creation or update collects issues across all decorated fields, and a decorated function call collects issues across all decorated parameters. Issues preserve declaration and evaluation order. Separate operations throw separate ValidationError values and are never merged.
interface SignupInput {
@minLength(3)
username: string;
@email()
email: string;
}
const readUsername = (): string => "a";
const readEmail = (): string => "invalid";
const buildSignup = (): SignupInput throws ValidationError => {
return {
username: readUsername(),
email: readEmail(),
};
};
const main = (): void => {
try {
const input: SignupInput = buildSignup();
print(input.username); // "a"
} catch (error: ValidationError) {
match (error.issues.length === (1 as usize)) {
(true) => {
const issue = error.issues[0];
print(issue.target); // "username"
print(issue.message); // "must be at least 3 characters"
}
_ => {
for (const issue of error.issues) {
print(issue.target); // field name
print(issue.message); // validation message
}
}
}
}
};ValidationIssue is normally inferred when an item is read from error.issues; developers do not construct or throw it. Passing an issue to a read-only helper does not require writing &.
Reading and iterating error.issues inside the catch is the usual pattern. A direct move or return of error.issues is also safe: ownership follows the returned array instead of being released with the caught error.
const printIssue = (issue: ValidationIssue): void => {
print(issue.validator); // "email"
print(issue.message); // "invalid e-mail"
};
const printValidation = (error: ValidationError): void => {
for (const issue of error.issues) {
printIssue(issue);
}
};Typed .env validation is the exception: invalid startup configuration is fatal because the application cannot start with an invalid environment.
@in and @notIn accept an inline homogeneous array or a module-level const array that can be fully resolved at compile time. The array may contain enum members. Runtime variables, let bindings, function calls and API values are rejected because decoration arguments are compile-time metadata. Typed .env schemas continue to use inline arrays because .env files have no tyrus symbol or import scope.
enum Role: string {
Admin = "admin",
User = "user",
}
const allowedRoles: Role[] = [Role.Admin, Role.User];
const authorize = (@in(allowedRoles) role: Role): void => {
print(role); // Role.Admin or Role.User
};Regex Validators
interface SlugInput {
@regex(/^[a-z0-9-]+$/)
slug: string;
}@regex uses the native Regex type. Supported flags are i, m, s and x; look-around and backreferences are intentionally not supported.
