You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS中使用class-validator校验hh:mm:ss格式时间方法

class-validator 校验12小时制纯时间字符串方案

@IsDateString() 仅支持ISO 8601标准的日期/日期时间字符串校验,无法适配hh:mm:ss格式的纯时间值,可根据业务场景选择以下两种实现方案:


方案1:内置装饰器+正则校验(无额外依赖,适合单场景使用)

直接使用class-validator内置的@Matches装饰器,通过正则严格匹配12小时制时间格式即可,替换原有DTO代码如下:

import {
  IsNotEmpty,
  Matches,
} from 'class-validator';

export class CreateFilmTime {
  // 校验规则:小时范围01-12,分、秒范围00-59,严格匹配hh:mm:ss格式
  @Matches(/^(0[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9])$/, {
    message: 'time需传入12小时制hh:mm:ss格式时间,例:10:13:06'
  })
  @IsNotEmpty()
  // 注意:前端传参为字符串类型,直接定义为string即可,避免Date对象转换带来的时区问题
  time: string;
}
  • 如果业务需要兼容不带前导零的小时格式(比如9:05:12),把正则替换为/^(0?[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9])$/即可。
  • 主流ORM(比如TypeORM、Prisma)对MySQL/PostgreSQL的time类型字段,都支持直接接收该格式的字符串入库,不需要额外做类型转换。

方案2:自定义校验装饰器(适合多场景复用)

如果项目中有多个接口需要做相同的时间格式校验,可以封装自定义装饰器统一维护规则:

  1. 首先编写自定义校验逻辑:
import { 
  registerDecorator, 
  ValidationOptions, 
  ValidatorConstraint, 
  ValidatorConstraintInterface 
} from 'class-validator';

@ValidatorConstraint({ async: false })
class Is12HourTimeConstraint implements ValidatorConstraintInterface {
  validate(value: unknown): boolean {
    if (typeof value !== 'string') return false;
    return /^(0[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9])$/.test(value);
  }

  defaultMessage(): string {
    return '时间必须为12小时制hh:mm:ss格式';
  }
}

export function Is12HourTime(validationOptions?: ValidationOptions) {
  return function (target: Object, propertyName: string) {
    registerDecorator({
      target: target.constructor,
      propertyName,
      options: validationOptions,
      constraints: [],
      validator: Is12HourTimeConstraint,
    });
  };
}
  1. 在DTO中直接引入使用:
import { IsNotEmpty } from 'class-validator';
import { Is12HourTime } from '你的校验装饰器存放路径';

export class CreateFilmTime {
  @Is12HourTime()
  @IsNotEmpty()
  time: string;
}

内容的提问来源于stack exchange,提问作者Christian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 14:09:22