question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to describe validators for two possible types: array or string?

See original GitHub issue

How to describe validators for two possible types: array or string?

Two decorators seems not working.

@IsBoolean()
@IsString()
private readonly foo: boolean | string;

Issue Analytics

  • State:open
  • Created 6 years ago
  • Reactions:14
  • Comments:17 (2 by maintainers)

github_iconTop GitHub Comments

18reactions
NoNameProvidedcommented, Mar 17, 2018

How about a signature like:

@IsType(Array<(val: any) => boolean>)
@IsType([
 val => typeof val == 'string',
 val => typeof val == 'boolean',
])
private readonly foo: boolean | string;
15reactions
ZBAGIcommented, Mar 25, 2020

@NoNameProvided Personally i’m against complex logic in decorator definitions. Imagine having repeat those val => typeof val == 'string' in every property you want to validate. It quickly gets messy. Especially when you will need to change the logic of validating - then you will need to look for all references and change them one by one.

I suggest you to implement similar solution to the one i posted here. Or if it’s common to validate multi-typed properties in your project, you can use custom decorator factory to specify which type you want to validate.

import { registerDecorator, ValidationArguments, ValidationOptions, Validator } from "class-validator";


const typeValidator = {
    "string": function (value: any, args: ValidationArguments) {
        const validator = new Validator();
        return validator.isString(value);
    },
    "int": function (value: any, args: ValidationArguments) {
        const validator = new Validator();
        return validator.isInt(value);
    }
// Add more here
};

export function IsType(types: (keyof (typeof typeValidator))[], validationOptions?: ValidationOptions) {
    return function (object: Object, propertyName: string) {
        registerDecorator({
            name: "wrongType",
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    return types.some(v => typeValidator[v](value, args));
                },
                defaultMessage(validationArguments?: ValidationArguments) {
                    const lastType = types.pop();
                    if (types.length == 0)
                        return `Has to be ${lastType}`;
                    return `Can only be ${types.join(", ")} or ${lastType}.`;
                }
            }
        });
    };
}

And then usage is very simple and clean:

class example {
    @IsType(["string", "int"])
    public someValue: number | string;
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Multiple Types - JSON Schema
The basic declaration of multiple types is through the "type" keyword, where we can now have an array containing different types. For example,...
Read more >
validation value having two possible types - Stack Overflow
public function boot() { Validator::extend('string_or_array', ... by checking type of the variable in order to add the appropriate rule as:
Read more >
typestack/class-validator - Gitter
How to describe validators for two possible types : array or string? Two decorators seems not working. @IsBoolean() @IsString() private readonly foo: boolean ......
Read more >
Dynamic type validation in TypeScript - LogRocket Blog
In the two other methods, the validator and the type can be seen as different entities: the validator will take the incoming object...
Read more >
Types - Superstruct
You can also define your own custom validation functions using the struct ... [1, 2, 3] ... array structs accept a list of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found