# Pattern Decorator validation swagger schema

Module
import { Pattern } from "@tsed/common"
Source/packages/common/src/jsonschema/decorators/pattern.ts

# Overview

function Pattern(pattern: string | RegExp): (...parameters: any[]) => any;

# Description

The pattern and Pattern Properties keywords use regular expressions to express constraints. The regular expression syntax used is from JavaScript (ECMA 262, specifically). However, that complete syntax is not widely supported, therefore it is recommended that you stick to the subset of that syntax described below.

WARNING

This decorator will be removed in v7. For v6 user, use from @tsed/schema instead of @tsed/common.

A single unicode character (other than the special characters below) matches itself.

  • ^: Matches only at the beginning of the string.
  • $: Matches only at the end of the string.
  • (...): Group a series of regular expressions into a single regular expression.
  • |: Matches either the regular expression preceding or following the | symbol.
  • [abc]: Matches any of the characters inside the square brackets.
  • [a-z]: Matches the range of characters.
  • [^abc]: Matches any character not listed.
  • [^a-z]: Matches any character outside of the range.
  • +: Matches one or more repetitions of the preceding regular expression.
  • *: Matches zero or more repetitions of the preceding regular expression.
  • ?: Matches zero or one repetitions of the preceding regular expression.
  • +?, *?, ??: The *, +, and ? qualifiers are all greedy; they match as much text as possible. Sometimes this behavior isn’t desired and you want to match as few characters as possible.
  • {x}: Match exactly x occurrences of the preceding regular expression.
  • {x,y}: Match at least x and at most y occurrences of the preceding regular expression.
  • {x,}: Match x occurrences or more of the preceding regular expression.
  • {x}?, {x,y}?, {x,}?`: Lazy versions of the above expressions.

# Example

class Model {
   @Pattern("^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$")
   @Pattern(/^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$/)
   property: string;
}
1
2
3
4
5

# With primitive type

class Model {
   @Pattern(/^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$/)
   property: string;
}
1
2
3
4
{
  "type": "object",
  "properties": {
    "property": {
      "type": "string",
      "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
    }
  }
}
1
2
3
4
5
6
7
8
9

# With array type

class Model {
   @CollectionOf(string)
   @Pattern(/^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$/)
   property: string[];
}
1
2
3
4
5

Will produce:

{
  "type": "object",
  "properties": {
    "property": {
      "type": "array",
      "items": {
        "type": "string",
        "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
      }
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12