From 4a57dcfd8dcd32ae08daaea90e1e81d93f40e4f1 Mon Sep 17 00:00:00 2001 From: Pawel Kozlowski Date: Wed, 5 Oct 2016 01:14:23 +0200 Subject: [PATCH] fix(forms): properly validate empty strings with patterns (#11450) --- modules/@angular/forms/src/validators.ts | 1 - modules/@angular/forms/test/validators_spec.ts | 9 +++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/modules/@angular/forms/src/validators.ts b/modules/@angular/forms/src/validators.ts index e0cd411c7e..865cdc0d0d 100644 --- a/modules/@angular/forms/src/validators.ts +++ b/modules/@angular/forms/src/validators.ts @@ -96,7 +96,6 @@ export class Validators { */ static pattern(pattern: string): ValidatorFn { return (control: AbstractControl): {[key: string]: any} => { - if (isPresent(Validators.required(control))) return null; let regex = new RegExp(`^${pattern}$`); let v: string = control.value; return regex.test(v) ? null : diff --git a/modules/@angular/forms/test/validators_spec.ts b/modules/@angular/forms/test/validators_spec.ts index 921965171d..280a3241fd 100644 --- a/modules/@angular/forms/test/validators_spec.ts +++ b/modules/@angular/forms/test/validators_spec.ts @@ -91,6 +91,9 @@ export function main() { it('should not error on null', () => { expect(Validators.pattern('[a-zA-Z ]*')(new FormControl(null))).toEqual(null); }); + it('should not error on null value and "null" pattern', + () => { expect(Validators.pattern('null')(new FormControl(null))).toEqual(null); }); + it('should not error on valid strings', () => { expect(Validators.pattern('[a-zA-Z ]*')(new FormControl('aaAA'))).toEqual(null); }); @@ -100,6 +103,12 @@ export function main() { 'pattern': {'requiredPattern': '^[a-zA-Z ]*$', 'actualValue': 'aaa0'} }); }); + + it('should error on failure to match empty string', () => { + expect(Validators.pattern('[a-zA-Z]+')(new FormControl(''))).toEqual({ + 'pattern': {'requiredPattern': '^[a-zA-Z]+$', 'actualValue': ''} + }); + }); }); describe('compose', () => {