Skip to content

support RegExp instances in @ApiProperty({ pattern }) #3719

@leandroluk

Description

@leandroluk

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Currently, when defining a validation pattern in @ApiProperty, if a developer has a centralized RegExp object, they must manually access the .source property to avoid serialization issues in the OpenAPI spec.

As shown in the example below, this adds boilerplate and is counter-intuitive for developers who are used to passing the regex object directly to other libraries (like class-validator's @Matches):

// Current way
@ApiProperty({ pattern: PASSWORD_REGEX.source })
readonly password!: string;

Describe the solution you'd like

I would like the @ApiProperty decorator (and related internal metadata scanners) to automatically detect if the value provided to the pattern property is an instanceof RegExp. If it is, the library should internally extract the .source string.

Proposed internal logic:

const pattern = options.pattern instanceof RegExp 
  ? options.pattern.source 
  : options.pattern;

Considered drawbacks: - None identified. It is a non-breaking change as it only adds support for a type that previously might have caused invalid output or type errors.

Teachability, documentation, adoption, migration strategy

This change is completely backward compatible.

@ApiProperty({ pattern: /^[a-zA-Z0-9]+$/.source })

After (Improved DX):

@ApiProperty({ pattern: /^[a-zA-Z0-9]+$/ })

Users would no longer need to remember to call .source, making the decorator behavior consistent with how class-validator handles regex. We can update the "OpenAPI (Swagger) > Types and Parameters" section of the docs to show this cleaner syntax.

What is the motivation / use case for changing the behavior?

The motivation is to improve Developer Experience (DX) and code readability. In many projects, Regex patterns are shared between validation (DTOs) and documentation. Since class-validator accepts the RegExp object directly, it feels inconsistent that @nestjs/swagger requires the string source.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions