Skip to content

pattern ​

The string matches a regular expression.

Signature ​

ts
function pattern(re: RegExp, msg?: Message): Action<string>

Parameters ​

ParameterTypeDescription
reRegExpRegular expression
msgMessageCustom error message. A string with {params} or a function

Error codes ​

CodeWhenDefault message
patternThe string does not matchInvalid format

You can change the texts: see Messages & i18n.

Notes ​

  • Use ^ and $: without them /\d+/ accepts 'abc1', because it finds a digit inside the string.
  • The g flag is safe — lastIndex is reset before each check.

Examples ​

Phone ​

ts
pipe(string(), pattern(/^\+1\d{10}$/, 'Format: +1XXXXXXXXXX'))

Slug ​

ts
pipe(string(), pattern(/^[a-z0-9]+(-[a-z0-9]+)*$/))

See also ​