Class

PatternValidator

PatternValidator(messageopt)

Constructor

# new PatternValidator(messageopt)

The PatternValidator checks if a string value matches a specified regular expression pattern. It supports both RegExp objects and string representations of patterns, including those with flags. This validator is the foundation for specialized validators like EmailValidator and URLValidator, and is typically used with the @pattern decorator.

Validator for checking if a string matches a regular expression pattern

sequenceDiagram participant C as Client participant V as PatternValidator C->>V: new PatternValidator(message) C->>V: hasErrors(value, options) alt value is empty V-->>C: undefined (valid) else pattern is missing V-->>C: Error: Missing Pattern else pattern is string V->>V: getPattern(pattern) end V->>V: Reset pattern.lastIndex V->>V: Test value against pattern alt pattern test passes V-->>C: undefined (valid) else pattern test fails V-->>C: Error message end
Parameters:
Name Type Attributes Description
message string <optional>

Custom error message to display when validation fails, defaults to DEFAULT_ERROR_MESSAGES#PATTERN

View Source validation/Validators/PatternValidator.ts, line 22

Example
```typescript
// Create a pattern validator with default error message
const patternValidator = new PatternValidator();

// Create a pattern validator with custom error message
const customPatternValidator = new PatternValidator("Value must match the required format");

// Validate using a RegExp object
const regexOptions = { pattern: /^[A-Z][a-z]+$/ };
patternValidator.hasErrors("Hello", regexOptions); // undefined (valid)
patternValidator.hasErrors("hello", regexOptions); // Returns error message (invalid)

// Validate using a string pattern
const stringOptions = { pattern: "^\\d{3}-\\d{2}-\\d{4}$" };
patternValidator.hasErrors("123-45-6789", stringOptions); // undefined (valid)

// Validate using a string pattern with flags
const flagOptions = { pattern: "/^hello$/i" };
patternValidator.hasErrors("Hello", flagOptions); // undefined (valid)
```

Extends

Methods

# hasErrors(value, options) → {string|undefined}

Validates that the provided string matches the pattern specified in the options. If the pattern is provided as a string, it's converted to a RegExp object using the getPattern method. The method resets the pattern's lastIndex property to ensure consistent validation results for patterns with the global flag.

Checks if a string matches a regular expression pattern

Parameters:
Name Type Description
value string

The string to validate against the pattern

options PatternValidatorOptions

Configuration options containing the pattern

Overrides:
See:

View Source validation/Validators/PatternValidator.ts, line 173

If no pattern is provided in the options

Error

Error message if validation fails, undefined if validation passes

string | undefined