gitmyhub

class-validator

TypeScript ★ 12k updated 2mo ago

Decorator-based property validation for classes.

A TypeScript library that lets you attach validation rules as small decorators on class properties, then check any object against those rules with a single function call and receive a detailed error list.

TypeScriptNode.jssetup: easycomplexity 2/5

class-validator is a TypeScript library that lets you declare rules for what values are acceptable on the properties of a class, then automatically check whether a given object follows those rules. The typical use case is validating data that arrives at a server, like a form submission or API request body, before trusting it or saving it to a database.

You attach small annotations called decorators directly to the properties of your class. For example, adding @IsEmail() to an email property means the library will confirm the value looks like a valid email address when you run validation. There are built-in decorators for common checks: minimum and maximum length for strings, numeric ranges, date formats, URL formats, whether a value is present at all, and many others. You can also write your own custom validators if the built-in ones do not cover your case.

Running validation is one function call: validate(instance) returns a list of errors. Each error identifies which property failed, what value was provided, and which rule was violated. Error messages can be customized with static strings or with functions that receive the actual value and constraint details, so you can return different messages depending on what went wrong.

The library supports more than flat objects. You can validate arrays of values, nested objects, maps, and sets. Validation can be grouped so that different rules apply in different contexts, such as stricter checks during creation versus updates. There is also a whitelisting mode that rejects any properties not explicitly declared in the class, which protects against unexpected extra data.

class-validator works in both Node.js and browser environments and can be used with or without decorators depending on your setup. The full README is longer than what was shown.

Where it fits