It's Day 4 of Launch Week and we're back with another launch...
Today, we’re excited to announce advanced value-based validation support for Encore.ts. Here’s everything you need to know about this game-changing feature and how it works.
Encore.ts has always made defining request and response types intuitive with ordinary TypeScript types.
By leveraging these types, Encore ensures both compile-time and runtime type safety.
If a request doesn’t conform to the specified type, Encore automatically responds with a 400
error, keeping your API robust.
Within the API handler, you also benefit from full type-safety for the params object.
But beyond ensuring all the expected fields are present with the right types, it's also important to be able to validate that the values are within acceptable ranges, or match specific patterns.
We're excited to announce that Encore.ts now has support for value-based validation!
Like the rest of Encore, this new functionality makes direct of use the TypeScript type system to define the validation rules.
Here's what it looks like:
import { Min, Max, MinLen, MaxLen, IsEmail, IsURL } from "encore.dev/validate";
export interface Params {
// A number between 3 and 1000 (inclusive).
foo: number & (Min<3> & Max<1000>);
// A string between 5 and 20 characters long.
bar: string & (MinLen<5> & MaxLen<20>);
// A string that is either a URL or an email address.
urlOrEmail: string & (IsURL | IsEmail);
// An array of up to 10 email addresses.
emails: Array<string & IsEmail> & MaxLen<10>;
}
As you can see, it's easy to add value-based validation rules to any field.
You can combine validation rules using &
and |
(for 'and'/'or').
The full list of validation rules available in Encore.ts includes:
Min
/Max
: validating minimum/maximum values for numbersMinLen
/MaxLen
: validating minimum/maximum lengths for strings and arraysIsURL
/IsEmail
: validating that a string is a URL or email addressStartsWith
/EndsWith
/MatchesRegexp
: validating that a string matches a specific patternLearn more in the documentation.
Encore.ts achieves exceptional performance by running validations in Rust, rather than in JavaScript. This is made possible by the fact that Encore.ts uses static analysis of the TypeScript type system to pre-compile what validation rules apply to each field.
This approach outpaces validation frameworks like Zod and TypeBox, providing speed without sacrificing usability, and enables Encore.ts to be 9x faster than Express.js and 3x faster than Elysia and Hono.
See our benchmarks to learn more
If you're already using Encore, update using encore version update
.
If you're new to Encore, install using the instructions below and then create an example app using encore app create
.
$ brew install encoredev/tap/encore
If you have questions or just want to hang out with other Encore developers, join our community on Discord.