michallytek / class-transformer-validator Goto Github PK
View Code? Open in Web Editor NEWA simple plugin for class-transformer and class-validator which combines them in a nice and programmer-friendly API.
License: MIT License
A simple plugin for class-transformer and class-validator which combines them in a nice and programmer-friendly API.
License: MIT License
This is my package.json dependencies:
"class-transformer-validator": "^0.8.0",
"class-validator": "^0.11.0",
and I'm getting yarn error:
"class-transformer-validator#class-validator@^0.10.1" doesn't satisfy found match of "[email protected]"
export class CreateEventDto {
@IsString()
@Length(5, 255)
title: string;
@IsString()
@Length(5, 255)
location: string;
@IsString()
@IsNotEmpty()
@Length(5, 255)
description: string;
@IsUrl()
url?: string;
@IsString({ each: true })
images: string[];
@IsDateString()
startDate: Date;
@IsDateString()
endDate: Date;
}
export class UpdateEventDto implements Partial<CreateEventDto> {}
{
"target": {
"name": "AuraEd workshop on web automation with python"
},
"property": "title",
"children": [],
"constraints": {
"length": "title must be longer than or equal to 5 characters",
"isString": "title must be a string"
}
},
{
"target": {
"name": "AuraEd workshop on web automation with python"
},
"property": "location",
"children": [],
"constraints": {
"length": "location must be longer than or equal to 5 characters",
"isString": "location must be a string"
}
},
{
"target": {
"name": "AuraEd workshop on web automation with python"
},
"property": "description",
"children": [],
"constraints": {
"length": "description must be longer than or equal to 5 characters",
"isNotEmpty": "description should not be empty",
"isString": "description must be a string"
}
},
{
"target": {
"name": "AuraEd workshop on web automation with python"
},
"property": "url",
"children": [],
"constraints": {
"isUrl": "url must be an URL address"
}
},
{
"target": {
"name": "AuraEd workshop on web automation with python"
},
"property": "startDate",
"children": [],
"constraints": {
"isDateString": "startDate must be a ISOString"
}
},
{
"target": {
"name": "AuraEd workshop on web automation with python"
},
"property": "endDate",
"children": [],
"constraints": {
"isDateString": "endDate must be a ISOString"
}
}
{
"name": "AuraEd workshop on web automation with python"
}
I can validate nested objects, and I can make sure that certain property is an array. However, the validator does not care if the elements in the array are valid or not. What am I forgetting here?
export class Album {
@IsString()
@Expose()
@IsDefined()
name!: string;
}
export class Photo {
@IsNumber()
@Expose()
@IsDefined()
id!: number;
@Expose()
@IsDefined()
@IsArray()
@Type(() => Album)
albums!: Album[];
}
const object = {
name: "Juan Ramon Riquelme",
albums: [{
noName: "Felipe"
}]
}
// This line succeeds, but it should fail!
transformAndValidate(Photo, object, {
transformer: { excludeExtraneousValues: true },
validator: { forbidUnknownValues: true }
}).then(console.log).catch(console.error);
I have written a complete reproducer and pushed it here: https://gitlab.com/albertodiazdorado/class-transform-validator-issue
To reproduce:
git clone https://gitlab.com/albertodiazdorado/class-transform-validator-issue.git
pushd class-transform-validator-issue
yarn install # or npm install
yarn start # or npm start
such as "-0.8" a valid numeric string, i get an error.
seems like the regex used to validate that missing a dot
like yup noUnknown. not only validate the object but also remove properties I didn't define.
console.err(error)
Property 'err' does not exist on type 'console'.
Replace it with 'error':
console.error(something)
I'm currently using this package with a helper to create type guards:
/** Create a type guard function for a class decorated with validators. */
export function isValidFactory<T extends object>(classType: ClassType<T>): (instance: object) => instance is T {
return (instance: object): instance is T => {
try {
transformAndValidateSync(classType, instance)
return true
} catch (err) {
return false
}
}
}
Would you be interested in a PR that adds this helper?
I recently updated to class-transformer 0.2.0, becuase I wanted to use the discriminator
feature that they introduced. From my brief tests it looks like it still works with this package, but my use cases are not too complicated, so I can't say everything's ok :) Anyway, it may be worth releasing with updated deps, probably as v0.7 since it's theoretically a breaking change for class-transformer.
If used with ng2, zone.js throws multiple errors in console.
when i install class-validator, class-transformer get removed, and when i install class-transformer again, class validator gets removed.
yarn version : 1.3.2
npm version : 5.5.1
node version: 8.9.1
angular/cli: 1.6.4
angular-devkit/build-optimizer: 0.0.38
angular-devkit/core: 0.0.25
angular-devkit/schematics: 0.0.48
ngtools/json-schema: 1.1.0
ngtools/webpack: 1.9.4
schematics/angular: 0.1.13
schematics/schematics: 0.0.13
typescript: 2.2.2
webpack: 3.10.0
Now, without this feature my only way is call transformer and validator manually
Hello,
I have this code :
import 'reflect-metadata'
import { IsDate, ValidateNested, validate } from 'class-validator'
import { Type, plainToClass } from 'class-transformer'
import { transformAndValidate } from 'class-transformer-validator'
export class User {
@Type(() => Date)
@IsDate()
availabilityDate?: Date
}
export class Parent {
@ValidateNested()
@Type(() => User)
user?: User
}
const body = {
user: {
availabilityDate: new Date().toISOString(),
},
}
const classTransformer = plainToClass(Parent, body) as any
console.log(
'Typeof',
Object.prototype.toString.call(classTransformer.user.availabilityDate) === '[object Date]'
) // true
validate(classTransformer).then((errors) => {
console.log(errors) // []
})
transformAndValidate(User, body)
.then((resultValidator: any) => {
// Don't pass here
console.log(
Object.prototype.toString.call(resultValidator.user.availabilityDate) === '[object Date]'
) // Should be true
})
.catch((err) => {
console.log(err) // -> constraints: { isDate: 'availabilityDate must be a Date instance' }
})
As you can see, validate don't returns errors but transformAndValidate do. Did I miss something ?
Thanks
It should relate to this issue in class-transformer after they released 0.2.2 yesterday
import { transformAndValidate } from 'class-transformer-validator';
class User {
@IsEmail()
identifier!: string;
@IsString()
password!: string;
}
const user: User = {
identifier: '[email protected]',
password: 'password123',
};
const userJson: string = JSON.stringify(user);
await transformAndValidate(User, userJson)
.then(async (): Promise<void> => Promise.resolve())
.catch(async (err: Error): Promise<never> => Promise.reject(err));
Throw error
TypeError: Reflect.getMetadata is not a function
Which was working fine before(before they upgrade to 0.2.2)
By adding
import 'reflect-metadata';
at the top solved this issue.
Would it be possible to add wrapping of synchronous validation ?
I don't understand why creating custom validators need require so much boilerplate with class creation etc. Surely there should be a simple way to create custom validators that take messages? E.g.
@IsString
@IsNotEmpty
@ValidIf(o.section === "SomeSectionName", { message: "Wrong section" })
myProperty!: string
Am I missing a simple way of doing this without creating a constraint class and then registering a decorator or using the @Validate(MyConstraint, { message: "Wrong section" })
form?
Using class-transformer-validator
results in google-libphonenumber
being included in the webpack bundle (even though tree shaking is enabled and no phone number validators are being used).
This was fixed in class-validator
itself, see:
I'm wondering if there is an "easy" fix for this package?
Hi,
I have the following:
export class Onset {
@IsNotEmpty( { message: 'Input required' } )
@MinLength( 6, { message: minLength6Fn } )
mode: string
}
export function minLength6Fn( args: ValidationArguments ) {
switch ( args.value.length ) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return `Too short, minimum length is ${args.constraints[ 0 ]} characters, but actual is ${args.value.length}`
}
}
Validation is done as shown below:
onset = new Onset()
onset.model = 'Sudden'
transformAndValidate( Onset, currentValue )
.then( ( onset: Onset ) => {
} )
.catch( errors => {
console.log( `onset errors | ${JSON.stringify( errors ) }` )
console.log( errors )
let propError = findPropertyValidationErrors( errors, 'mode' )
console.log( propError )
} )
The validation error printed to console is '["Too short, minimum length is 6 characters, but actual is 5"]
The ${args.value.length} in return Too short, minimum length is ${args.constraints[ 0 ]} characters, but actual is ${args.value.length}
is NOT reflecting the true length of the input.
Is this a bug?
There should be done support for array transforming and validation
Currently transformAndValidate(classType, jsonString)
returns Promise<classType>
even if jsonString
is a JSON array string. This feature need new type definition (Promise<classType|Array<classType>>
) which will require type assertion from lib consumers.
Could you change 'object' to 'Object' in index.d.ts please?
I have got 10 errors in index.d.ts file like this:
class-transformer-validator/index.d.ts:19:56
Cannot find name 'object'.
How about extending this project with some new decorators that would make use of the fact that both libraries are available?
For example: instead of using @Type(() => Foo)
and @IsInstance(Foo, {each: true})
and @IsArray()
one could use a single decorator like @IsArrayOf(Foo)
which would configure both class-transformer and class-validator with less code.
The types for transformAndValidate
is declared as:
export declare function transformAndValidate<T extends object>(classType: ClassType<T>, object: object, options?: TransformValidationOptions): Promise<T>;
Where the return is typed as <T>
However, if the return of transformAndValidate
is an array of transformed instances then you need t do something like this to get the typing correct:
as unknown as InstanceClass[]
Since this package uses both class-validator and class-transformer, and many users complain on applying @expose() on all fields in order to remove extraneous values, wouldn't it be possible to give an option to levarage the validation decorators?
Something like "excludeUnvalidatedFields"?
Or, perhaps, we could have something like @IsStringExpose(), that wraps both @IsString() and @expose() ? I created this Gist as reference: https://gist.github.com/pauloendoh/f7d3194bae2ff121e78ce45589bd4ab2
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.