class-validator#registerDecorator TypeScript Examples

The following examples show how to use class-validator#registerDecorator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: user.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
// we have to copy the container validator as to avoid cyclical imports
export function ContainerID(validationOptions?: ValidationOptions) {
    return (object: object, propertyName: string) => {
        registerDecorator({
            name: 'ContainerID',
            target: object.constructor,
            propertyName,
            constraints: [],
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    return value instanceof Container && typeof value.id === 'string';
                },
            },
        });
    };
}
Example #2
Source File: IsInRange.ts    From tatum-blockchain-connector with MIT License 6 votes vote down vote up
IsInRange = (min: number, max: number, validationOptions?: ValidationOptions) => function (object: Object, propertyName: string) {
  registerDecorator({
    name: 'isInRange',
    target: object.constructor,
    propertyName: propertyName,
    constraints: [min, max],
    options: {
      message: `${propertyName} must be between ${min} and ${max}`,
      ...validationOptions
    },
    validator: {
      validate(value: any) {
        return new BigNumber(value).lte(max) && new BigNumber(value).gte(min)
      },
    },
  });
}
Example #3
Source File: is-username-already-exist.validator.ts    From nestjs-starter with MIT License 6 votes vote down vote up
export function IsUsernameAlreadyExist(validationOptions?: ValidationOptions) {
  return function (object: Record<string, any>, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsUsernameAlreadyExistConstraint,
    });
  };
}
Example #4
Source File: is-email-already-exist.validator.ts    From nestjs-starter with MIT License 6 votes vote down vote up
export function IsEmailAlreadyExist(validationOptions?: ValidationOptions) {
  return function (object: Record<string, any>, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsEmailAlreadyExistConstraint,
    });
  };
}
Example #5
Source File: validators.decorator.ts    From bank-server with MIT License 6 votes vote down vote up
export function IsPassword(
  validationOptions?: ValidationOptions,
): PropertyDecorator {
  return (object: any, propertyName: string) => {
    registerDecorator({
      propertyName,
      name: 'isPassword',
      target: object.constructor,
      constraints: [],
      options: validationOptions,
      validator: {
        validate(value: string, _args: ValidationArguments) {
          return /^[a-zA-Z0-9!@#$%^&*]*$/.test(value);
        },
      },
    });
  };
}
Example #6
Source File: IsEqualTo.ts    From tezos-academy with MIT License 6 votes vote down vote up
export function IsEqualTo(property: string, validationOptions?: ValidationOptions) {
  return (object: any, propertyName: string): any => {
    registerDecorator({
      name: 'isEqualTo',
      target: object.constructor,
      propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments): boolean {
          const [relatedPropertyName] = args.constraints
          const relatedValue = (args.object as any)[relatedPropertyName]
          return value === relatedValue
        },

        defaultMessage(args: ValidationArguments): string {
          const [relatedPropertyName] = args.constraints
          return `$property must match ${relatedPropertyName} exactly`
        },
      },
    })
  }
}
Example #7
Source File: custom-validators.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
export function IsPluginConfig(validationOptions?: ValidationOptions) {
    return (object: any, propertyName: string) => {
        registerDecorator({
            name: 'isPluginConfig',
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            validator: {
                validate(value: any, _args: ValidationArguments) {
                    if (isObjectLike(value)) {
                        return Object.entries(value).every(([_, v]) => {
                            if (isArray(v)) {
                                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                                // @ts-ignore
                                return Array.from(v).every(isString);
                            }

                            return isString(v) || isBoolean(v);
                        });
                    }

                    return false;
                },
                defaultMessage(args?: ValidationArguments) {
                    const expectedMsg = 'Expected "{ [key: string]: string | string[] | boolean }"';

                    if (!args) {
                        return expectedMsg;
                    }

                    const strValue = JSON.stringify(args.value);
                    return `${expectedMsg} on "${args.property}" but found "${strValue}" instead`;
                },
            },
        });
    };
}
Example #8
Source File: custom-validators.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
export function IsValidJWT() {
    return (object: Record<string, any>, propertyName: string) => {
        registerDecorator({
            name: 'isValidJWT',
            target: object.constructor,
            propertyName: propertyName,
            options: {
                message: 'Must be valid JWT token',
            },
            validator: {
                validate(value: any) {
                    const JWT_REGEX = /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/m;

                    if (!value || typeof value !== 'string') {
                        return false;
                    }

                    const match = value.match(JWT_REGEX);

                    return Boolean(match && match[0].length === value.length);
                },
            },
        });
    };
}
Example #9
Source File: custom-validators.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
export function IsValidUrl() {
    return (object: Record<string, any>, propertyName: string) => {
        registerDecorator({
            name: 'isValidUrl',
            target: object.constructor,
            propertyName: propertyName,
            options: {
                message: 'Must be valid URL',
            },
            validator: {
                validate(value: any) {
                    try {
                        const url = new URL(value);
                        return Boolean(url.protocol);
                    } catch (e) {
                        return false;
                    }
                },
            },
        });
    };
}
Example #10
Source File: metatype_relationship_pair.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
// any specific validators should be specified here
export function MetatypeRelationshipPairID(validationOptions?: ValidationOptions) {
    return (object: object, propertyName: string) => {
        registerDecorator({
            name: 'MetatypeRelationshipPairID',
            target: object.constructor,
            propertyName,
            constraints: [],
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    return value instanceof MetatypeRelationshipPair && typeof value.id! === 'string';
                },
            },
        });
    };
}
Example #11
Source File: metatype_relationship.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
// any specific validators should be specified here
export function MetatypeRelationshipID(validationOptions?: ValidationOptions) {
    return (object: object, propertyName: string) => {
        registerDecorator({
            name: 'MetatypeRelationshipID',
            target: object.constructor,
            propertyName,
            constraints: [],
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    return value instanceof MetatypeRelationship && typeof value.id! === 'string';
                },
            },
        });
    };
}
Example #12
Source File: metatype.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
export function MetatypeID(validationOptions?: ValidationOptions) {
    return (object: object, propertyName: string) => {
        registerDecorator({
            name: 'MetatypeID',
            target: object.constructor,
            propertyName,
            constraints: [],
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    return value instanceof Metatype && typeof value.id! === 'string';
                },
            },
        });
    };
}
Example #13
Source File: match.ts    From node-experience with MIT License 6 votes vote down vote up
export function Match(property: string, validationOptions?: ValidationOptions)
{
    return (object: any, propertyName: string) =>
    {
        registerDecorator({
            target: object.constructor,
            propertyName,
            options: validationOptions,
            constraints: [property],
            validator: MatchConstraint
        });
    };
}
Example #14
Source File: user.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
/*
 These final operations are class-validator specific property validations
*/
export function UserID(validationOptions?: ValidationOptions) {
    return (object: object, propertyName: string) => {
        registerDecorator({
            name: 'UserID',
            target: object.constructor,
            propertyName,
            constraints: [],
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    return value instanceof User && typeof value.id === 'string';
                },
            },
        });
    };
}
Example #15
Source File: is-url.validator.ts    From etherspot-sdk with MIT License 6 votes vote down vote up
export function IsUrl(validationOptions: ValidationOptions = {}) {
  return (object: any, propertyName: string) => {
    registerDecorator({
      propertyName,
      options: {
        message: `${propertyName} must be url`,
        ...validationOptions,
      },
      name: 'isUrl',
      target: object.constructor,
      constraints: [],
      validator: {
        validate(value: string): boolean {
          return isUrl(value);
        },
      },
    });
  };
}
Example #16
Source File: is-hex.validator.ts    From etherspot-sdk with MIT License 6 votes vote down vote up
export function IsHex(
  options: {
    size?: number;
  } = {},
  validationOptions: ValidationOptions = {},
) {
  return (object: any, propertyName: string) => {
    const { size } = options;
    let message = `${propertyName} must be hex`;

    if (size > 0) {
      message = `${message} with ${size} size`;
    }

    registerDecorator({
      propertyName,
      options: {
        message,
        ...validationOptions,
      },
      name: 'isHex',
      target: object.constructor,
      constraints: [],
      validator: {
        validate(value: string): boolean {
          let result = utils.isHexString(value);

          if (result && size > 0) {
            result = value.length === size * 2 + 2;
          }

          return result;
        },
      },
    });
  };
}
Example #17
Source File: is-big-numberish.validator.ts    From etherspot-sdk with MIT License 6 votes vote down vote up
export function IsBigNumberish(
  options: {
    positive?: boolean;
  } = {},
  validationOptions: ValidationOptions = {},
) {
  return (object: any, propertyName: string) => {
    const { positive } = options;

    registerDecorator({
      propertyName,
      options: {
        message: `${propertyName} must be ${positive ? 'positive ' : ''}big numberish`,
        ...validationOptions,
      },
      name: 'IsBigNumberish',
      target: object.constructor,
      constraints: [],
      validator: {
        validate(value: any): boolean {
          let result = false;

          try {
            const bn = BigNumber.from(value);
            result = positive ? bn.gt(0) : bn.gte(0);
          } catch (err) {
            //
          }

          return result;
        },
      },
    });
  };
}
Example #18
Source File: is-address.validator.ts    From etherspot-sdk with MIT License 6 votes vote down vote up
export function IsAddress(options: ValidationOptions = {}) {
  return (object: any, propertyName: string) => {
    registerDecorator({
      propertyName,
      options: {
        message: `${propertyName} must be an address`,
        ...options,
      },
      name: 'isAddress',
      target: object.constructor,
      constraints: [],
      validator: {
        validate(value: any): boolean {
          return isAddress(value);
        },
      },
    });
  };
}
Example #19
Source File: IsFieldEqual.ts    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
IsFieldEqual = (target: string, validationOptions?: ValidationOptions) => {
  return (object: any, propertyName: string) => {
    registerDecorator({
      target: object.constructor,
      options: validationOptions,
      constraints: [target],
      propertyName,
      validator: IsFieldEqualConstraint,
    })
  }
}
Example #20
Source File: IsEntity.ts    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
IsEntityNotExists = (
  options: IsEntityOptions | Function,
  validationOptions?: ValidationOptions,
) => {
  return (object: any, propertyName: string) => {
    registerDecorator({
      target: object.constructor,
      options: validationOptions,
      constraints: [options, false],
      propertyName,
      validator: IsEntityConstraint,
    })
  }
}
Example #21
Source File: IsEntity.ts    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
IsEntityExists = (
  options: IsEntityOptions | Function,
  validationOptions?: ValidationOptions,
) => {
  return (object: any, propertyName: string) => {
    registerDecorator({
      target: object.constructor,
      options: validationOptions,
      constraints: [options, true],
      propertyName,
      validator: IsEntityConstraint,
    })
  }
}
Example #22
Source File: unique.validator.ts    From NestJs-youtube with MIT License 6 votes vote down vote up
export function IsUniqueTitle(validationOptions?: ValidationOptions) {
  return (object: object, propertyName: string) => {
    registerDecorator({
      target: object.constructor,
      propertyName,
      options: validationOptions,
      constraints: [],
      validator: UniqueTitleConstrainsts,
      async: true,
    });
  };
}
Example #23
Source File: is-bytes-like.validator.ts    From etherspot-sdk with MIT License 5 votes vote down vote up
export function IsBytesLike(options: ValidationOptions & { acceptText?: boolean } = {}) {
  return (object: any, propertyName: string) => {
    registerDecorator({
      propertyName,
      options: {
        message: `${propertyName} must be bytes like`,
        ...options,
      },
      name: 'IsBytesLike',
      target: object.constructor,
      constraints: [],
      validator: {
        validate(value: any): boolean {
          let result = false;

          try {
            if (value) {
              switch (typeof value) {
                case 'string':
                  if (options.acceptText) {
                    result = true;
                  } else {
                    result = utils.isHexString(value) && value.length % 2 === 0;
                  }
                  break;

                case 'object':
                  result = Array.isArray(value) && value.every((value) => typeof value === 'number');
                  break;
              }
            }
          } catch (err) {
            //
          }

          return result;
        },
      },
    });
  };
}