From f50c1da4e2ad755e8aaea1ee2124ad225d01c3b0 Mon Sep 17 00:00:00 2001 From: Pawel Kozlowski Date: Fri, 7 Oct 2016 00:12:09 +0200 Subject: [PATCH] fix(forms): properly validate blank strings with minlength (#12091) --- modules/@angular/forms/src/validators.ts | 14 ++++++------- .../@angular/forms/test/validators_spec.ts | 20 +++++++++++++++---- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/modules/@angular/forms/src/validators.ts b/modules/@angular/forms/src/validators.ts index 865cdc0d0d..f0bff67ecf 100644 --- a/modules/@angular/forms/src/validators.ts +++ b/modules/@angular/forms/src/validators.ts @@ -70,10 +70,9 @@ export class Validators { */ static minLength(minLength: number): ValidatorFn { return (control: AbstractControl): {[key: string]: any} => { - if (isPresent(Validators.required(control))) return null; - var v: string = control.value; - return v.length < minLength ? - {'minlength': {'requiredLength': minLength, 'actualLength': v.length}} : + const length = typeof control.value === 'string' ? control.value.length : 0; + return length < minLength ? + {'minlength': {'requiredLength': minLength, 'actualLength': length}} : null; }; } @@ -83,10 +82,9 @@ export class Validators { */ static maxLength(maxLength: number): ValidatorFn { return (control: AbstractControl): {[key: string]: any} => { - if (isPresent(Validators.required(control))) return null; - var v: string = control.value; - return v.length > maxLength ? - {'maxlength': {'requiredLength': maxLength, 'actualLength': v.length}} : + const length = typeof control.value === 'string' ? control.value.length : 0; + return length > maxLength ? + {'maxlength': {'requiredLength': maxLength, 'actualLength': length}} : null; }; } diff --git a/modules/@angular/forms/test/validators_spec.ts b/modules/@angular/forms/test/validators_spec.ts index 280a3241fd..83b0c2effb 100644 --- a/modules/@angular/forms/test/validators_spec.ts +++ b/modules/@angular/forms/test/validators_spec.ts @@ -51,11 +51,23 @@ export function main() { }); describe('minLength', () => { - it('should not error on an empty string', - () => { expect(Validators.minLength(2)(new FormControl(''))).toEqual(null); }); + it('should error on an empty string', () => { + expect(Validators.minLength(2)(new FormControl(''))).toEqual({ + 'minlength': {'requiredLength': 2, 'actualLength': 0} + }); + }); - it('should not error on null', - () => { expect(Validators.minLength(2)(new FormControl(null))).toEqual(null); }); + it('should error on null', () => { + expect(Validators.minLength(2)(new FormControl(null))).toEqual({ + 'minlength': {'requiredLength': 2, 'actualLength': 0} + }); + }); + + it('should error on undefined', () => { + expect(Validators.minLength(2)(new FormControl(null))).toEqual({ + 'minlength': {'requiredLength': 2, 'actualLength': 0} + }); + }); it('should not error on valid strings', () => { expect(Validators.minLength(2)(new FormControl('aa'))).toEqual(null); });