@rhangai/class-validator
v0.3.1
Published
Validate classes using decorators
Downloads
20
Readme
@rhangai/class-validator
Getting started
yarn add @rhangai/class-validator
Use it
import { Validate, validade, Trim, IsString, IsInt, ToInt } from '@rhangai/class-validator';
@Trim()
export class UserDto {
@IsString()
name!: string;
@IsString()
address!: string;
@IsInt()
intValue!: number;
@ToInt()
maybeIntValue!: number;
}
const obj = {
name: ' john doe',
address: 'my home address',
intValue: 1000,
maybeIntValue: '123', // or 123
};
const user = await validate(UserDto, obj);
Validators
IsObject()
Check if the property is an object of the given typeIsObject(() => Type)
Check if the property is validated against a given typeIsArray([ ...Validators ])
Check if the property is an array of the validatorsTrim(chars?)
Trim the stirng. This does not ensure the property is a string.IsNumeric()
Check if the prop is a numeric valueIsString()
Check if the prop is a stringIsLength({ min?, max? })
Check if the object has length
Utility
IsOptional()
Allow null | undefinedIsOneOf(validators: any[])
Check if any of the validators has passed
Sanitizers
Trim(chars?: string)
NormalizeEmail(options: any)
Blacklist(chars: string)
Whitelist(chars: string)
Creating validators
import { Validate } from '@rhangai/class-validator';
export const IsPassword = Validate([IsString(), IsLength({ min: 6 })]);
You can also use the validator interface to create a validator
interface Validator {
/// Test whether this property is valid or not
test?: (value: any, context: ValidatorContext) => boolean | Promise<boolean>;
/// Message when there is an error
message?: string;
/// If skips returns true, the validation will be skipped
skip?: (value: any, context: ValidatorContext) => ValidatorSkipResult | Promise<ValidatorSkipResult>;
/// Transform the property
transform?: (value: any, context: ValidatorContext) => unknown | Promise<unknown>;
}
const IsPassword = Validate({
test: (input) => {
return typeof input === 'string' && input.length >= 6;
},
});