# 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
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
message |
string
|
<optional> |
Custom error message to display when validation fails, defaults to |
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