A form input validation tool set
This library fully uses the advantages of decorators, make it smooth to write validation rules. This projects aims to be foundation component for the rest of @t2ee projects. It provides dependency injection and auto configuration functionalities.
npm i reflect-metadata @t2ee/core @t2ee/validation -S
class Message {
@NotNull
@Min(4)
message: string;
}
@Path('/')
@Component
class Controller {
@POST
@Path('/say')
say(@Valid @Body message: Message) {
// message should be at least 4 characters long
}
}
const IsEmail = CustomRule('IsEmail', 'should be valid email');
@ValidationRule('IsEmail')
class IsEmailRule implements Rule {
validate(value: any, parameter: any, meta, AutoWireMeta, args: any[]): boolean {
return /[\d\w]*\@[\d\w]*\.[\w]*/.test(value);
}
}
OR
const IsEmail = Pattern(/[\d\w]*\@[\d\w]*\.[\w]*/);
@Valid
is an essential decorator, it validates all the rules associated with a type. Without @Valid
, validations will not be triggered.
CustomRule(name: string, error: string, parameter?: any)
, returns a PropertyDecorator
. This binds necessary metadata to the class
@ValidationRule(name: string)
inject your implementation of a rule to the ValidationProvider
, where your rules are resolved, parsed and validated.
Rule
is a interface
guides you how should it be implmeented for a ValidationRule
.
dataType | description |
---|---|
null or undefined | not checked |
String | checks the length of the string |
Number | checks Number.toString() length |
Array | checks array length |
Object | checks keys’ length |
Any value shuold pass validation if the value is not null
nor undefined
.
It only validates the regex when value is string and not null
nor undefined
.