Class-validator: flag for @IsDateString() to validate date without time

Created on 26 Jul 2019  路  6Comments  路  Source: typestack/class-validator

It`s more feature request.
I think it would be nice to have ability validate date string without time using @IsDateString() decorator. For example, '2000-07-26', not '2000-07-26T00:00:01.967Z'. Cannot find how to do that not using @Matches() decorator.

feature

Most helpful comment

I create custom one.

import { registerDecorator, ValidationOptions } from 'class-validator';

export function IsOnlyDate(validationOptions?: ValidationOptions) {
  return function(object: Object, propertyName: string) {
    registerDecorator({
      name: 'IsOnlyDate',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [],
      options: {
        message: 'Please provide only date like 2020-12-08',
        ...validationOptions,
      },
      validator: {
        validate(value: any) {
          const regex = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/;
          return typeof value === 'string' && regex.test(value);
        },
      },
    });
  };
}

All 6 comments

Feel free to contribute :)

I agree. There should be two different functions one for checking isostring and another for plain date string

@vlapo i am taking this one

I create custom one.

import { registerDecorator, ValidationOptions } from 'class-validator';

export function IsOnlyDate(validationOptions?: ValidationOptions) {
  return function(object: Object, propertyName: string) {
    registerDecorator({
      name: 'IsOnlyDate',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [],
      options: {
        message: 'Please provide only date like 2020-12-08',
        ...validationOptions,
      },
      validator: {
        validate(value: any) {
          const regex = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/;
          return typeof value === 'string' && regex.test(value);
        },
      },
    });
  };
}

@jerryfreshworks as a little note - the provided validator passes 2020-02-31 as a correct date so it's rather a format validator than actually validating if the date exists.

anything ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

otbe picture otbe  路  5Comments

golozubov picture golozubov  路  5Comments

Eldar-X picture Eldar-X  路  3Comments

NoNameProvided picture NoNameProvided  路  3Comments

twittwer picture twittwer  路  6Comments