0.3.1 • Published 3 years ago

@rhangai/class-validator v0.3.1

Weekly downloads
9
License
MIT
Repository
github
Last release
3 years ago

@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 type
  • IsObject(() => Type) Check if the property is validated against a given type
  • IsArray([ ...Validators ]) Check if the property is an array of the validators
  • Trim(chars?) Trim the stirng. This does not ensure the property is a string.
  • IsNumeric() Check if the prop is a numeric value
  • IsString() Check if the prop is a string
  • IsLength({ min?, max? }) Check if the object has length

Utility

  • IsOptional() Allow null | undefined
  • IsOneOf(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;
	},
});
0.3.1

3 years ago

0.3.0

3 years ago

0.2.3

4 years ago

0.2.4

4 years ago

0.2.2

4 years ago

0.2.0

4 years ago

0.1.0

4 years ago

0.1.1

4 years ago

0.0.16

4 years ago

0.0.15

4 years ago

0.0.14

4 years ago

0.0.10

4 years ago

0.0.11

4 years ago

0.0.12

4 years ago

0.0.13

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.5

4 years ago

0.0.6

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago