Skip to content

Custom Validator ​

Custom validators let an application define validation rules without adding new built-in validators. They can be used on interface fields and function parameters, and run synchronously when the decorated value is checked.

Declaration ​

Declare a validator with validator function or validator const. Its first parameter must be explicitly typed as value; optional configuration parameters follow it and receive the positional arguments written in the decorator. The function returns the Validator union. A successful result is { isValid: true }; a failure returns { isValid: false, message: "..." }.

The compiler supplies the decorated field or parameter value as value. For example, @hasPrefix("user_") calls the validator with the value first and "user_" as its configuration argument. Use empty parentheses for validators without configuration, such as @hasNoSpaces().

Example ​

tyrus
type Validator = { isValid: true } | { isValid: false; message: string };

validator function hasPrefix(value: string, constraint: string): Validator {
    if (!value.startsWith(constraint)) {
        return { isValid: false, message: "Value must start with the configured prefix" };
    }
    return { isValid: true };
}

validator const hasNoSpaces = (value: string): Validator => {
    if (value.includes(" ")) {
        return { isValid: false, message: "Value cannot contain spaces" };
    }
    return { isValid: true };
};

interface UserInput {
    @hasPrefix("user_")
    @hasNoSpaces()
    username: string;
}

function acceptUsername(@hasNoSpaces() value: string): string {
    return value;
}

const main = (): void => {
    try {
        const user: UserInput = { username: "guest user" };
        print(user.username);
    } catch (error: ValidationError) {
        print(error.issues.length);
        print(error.issues[0].target);
        print(error.issues[0].validator);
        print(error.issues[0].message);
        print(error.issues[1].validator);
        print(error.issues[1].message);
    }
};

Returned Messages ​

A custom validator chooses its failure message by returning { isValid: false, message }. That message is included in the resulting ValidationIssue; the value being checked is not inserted automatically. A failed check throws ValidationError, so the enclosing function must catch it or declare throws ValidationError.