From f6dfd2ffed231d6aa423a2332f2b324d080a7688 Mon Sep 17 00:00:00 2001 From: AleksanderBodurri Date: Wed, 30 Sep 2020 04:42:01 -0400 Subject: [PATCH] docs(forms): add section under Validators.pattern detailing use of global and sticky flags gotcha (#39055) Due to how the global and sticky flag make RegExp objects stateful, adds section detailing how it is not recommended to use these flags for control validations. PR Close #39055 --- packages/forms/src/validators.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/packages/forms/src/validators.ts b/packages/forms/src/validators.ts index d45286a370a..38f247dda29 100644 --- a/packages/forms/src/validators.ts +++ b/packages/forms/src/validators.ts @@ -366,6 +366,25 @@ export class Validators { * * ``` * + * ### Pattern matching with the global or sticky flag + * + * `RegExp` objects created with the `g` or `y` flags that are passed into `Validators.pattern` + * can produce different results on the same input when validations are run consecutively. This is + * due to how the behavior of `RegExp.prototype.test` is + * specified in [ECMA-262](https://tc39.es/ecma262/#sec-regexpbuiltinexec) + * (`RegExp` preserves the index of the last match when the global or sticky flag is used). + * Due to this behavior, it is recommended that when using + * `Validators.pattern` you **do not** pass in a `RegExp` object with either the global or sticky + * flag enabled. + * + * ```typescript + * // Not recommended (since the `g` flag is used) + * const controlOne = new FormControl('1', Validators.pattern(/foo/g)); + * + * // Good + * const controlTwo = new FormControl('1', Validators.pattern(/foo/)); + * ``` + * * @param pattern A regular expression to be used as is to test the values, or a string. * If a string is passed, the `^` character is prepended and the `$` character is * appended to the provided string (if not already present), and the resulting regular