typescript simple validation
abstract
config:
// tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
WARN: This package is for learning only and cannot be used for production!!!
update
Please use version >= 2.2.2
Fix
class TestValidate {
private readonly name = 'joy'
@ValidateParams()
async getName(person: ValidatePerson) {
console.log(this.name) // fix this result: 'joy'
return 1
}
}
use
Users create custom validation rules themselves
regular check
import { IsNotEmpty, Length, Max, Min, Optional } from 'custom-validates'
class ValidateBaseInfo {
@IsNotEmpty({ message: 'name is not empty' })
name: string;
@Min({ message: 'age is greater than [value]', value: 18 })
@IsNotEmpty({ message: 'age is not empty' })
age: number;
@Length({ message: 'length is [value]', value: 18 })
@Optional()
certno?: string;
}
custom validation
import { FactoryValid } from 'custom-validates'
function IsMail({ message, value }) {
const fn = v => {
if (v) return true; // verify mail
}
return FactoryValid({ message, value }, fn)
}
class ValidateBaseInfo {
@IsMail({ message: 'mail format error' })
mail: string;
}
nest validation
import { IsNotEmpty, Length, Max, Min, Optional } from 'custom-validates'
class ValidateBaseInfo {
@Min({ message: 'age is greater than [value]', value: 18 })
@IsNotEmpty({ message: 'age is not empty' })
age: number;
height: number;
}
class ValidateBodyParams {
@Max({message: 'the id is less than [value]', value: 18})
id: number;
// deep: true; verify array
// optional: true; optional params
@Validate({ origin: ValidateBaseInfo, optional: true, deep: true })
base?: ValidateBaseInfo[]
}
verify
import { ValidateParams, IsNotEmpty, Min, Validate, ValidateObjectParmas } from 'custom-validates'
class ValidateBaseInfo {
@Min({ message: 'age is greater than [value]', value: 18 })
@IsNotEmpty({ message: 'age is not empty' })
age: number;
height: number;
}
class ValidateBodyParams {
@Max({message: 'the id is less than [value]', value: 18})
id: number;
@Validate({ origin: ValidateBaseInfo, optional: true })
base?: ValidateBaseInfo
}
const obj: ValidateBodyParams = {
id: 15
}
const base: ValidateBaseInfo = {
age: 17,
height: 172
}
/** verify class-function */
class Test {
@ValidateParams()
async validate(obj: ValidateBodyParams, base: ValidateBaseInfo): Promise<any> {
return 1
}
}
/** class validation */
const test = new Test()
const value = test.validate(obj, base)
console.log('value', value)
/** object validation */
const objectValue = ValidateObjectParmas([ValidateBaseInfo], [base])
console.log('objectValue', objectValue)