From 54bf17988874e3149c926b97b0b6f0677d4e49b5 Mon Sep 17 00:00:00 2001 From: ghetolay Date: Mon, 18 Sep 2017 22:28:36 +0200 Subject: [PATCH] feat(forms): handle string with and without line boundary on pattern validator (#19256) PR Close #19256 --- packages/forms/src/validators.ts | 9 ++++++++- packages/forms/test/validators_spec.ts | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/forms/src/validators.ts b/packages/forms/src/validators.ts index 8f8f6cfa70..63a962b051 100644 --- a/packages/forms/src/validators.ts +++ b/packages/forms/src/validators.ts @@ -163,7 +163,14 @@ export class Validators { let regex: RegExp; let regexStr: string; if (typeof pattern === 'string') { - regexStr = `^${pattern}$`; + regexStr = ''; + + if (pattern.charAt(0) !== '^') regexStr += '^'; + + regexStr += pattern; + + if (pattern.charAt(pattern.length - 1) !== '$') regexStr += '$'; + regex = new RegExp(regexStr); } else { regexStr = pattern.toString(); diff --git a/packages/forms/test/validators_spec.ts b/packages/forms/test/validators_spec.ts index 1cd9acdbb1..a30c4430be 100644 --- a/packages/forms/test/validators_spec.ts +++ b/packages/forms/test/validators_spec.ts @@ -270,6 +270,12 @@ import {map} from 'rxjs/operator/map'; it('should not error on "undefined" pattern', () => expect(Validators.pattern(undefined !)(new FormControl('aaAA'))).toBeNull()); + + it('should work with string containing line boundary', + () => expect(Validators.pattern('^[aA]*$')(new FormControl('aaAA'))).toBeNull()); + + it('should work with string not containing line boundary', + () => expect(Validators.pattern('[aA]*')(new FormControl('aaAA'))).toBeNull()); }); describe('compose', () => {