fix(forms): properly validate blank strings with minlength (#12091)

This commit is contained in:
Pawel Kozlowski 2016-10-07 00:12:09 +02:00 committed by Tobias Bosch
parent 0254ce1f6c
commit f50c1da4e2
2 changed files with 22 additions and 12 deletions

View File

@ -70,10 +70,9 @@ export class Validators {
*/ */
static minLength(minLength: number): ValidatorFn { static minLength(minLength: number): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => { return (control: AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null; const length = typeof control.value === 'string' ? control.value.length : 0;
var v: string = control.value; return length < minLength ?
return v.length < minLength ? {'minlength': {'requiredLength': minLength, 'actualLength': length}} :
{'minlength': {'requiredLength': minLength, 'actualLength': v.length}} :
null; null;
}; };
} }
@ -83,10 +82,9 @@ export class Validators {
*/ */
static maxLength(maxLength: number): ValidatorFn { static maxLength(maxLength: number): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => { return (control: AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null; const length = typeof control.value === 'string' ? control.value.length : 0;
var v: string = control.value; return length > maxLength ?
return v.length > maxLength ? {'maxlength': {'requiredLength': maxLength, 'actualLength': length}} :
{'maxlength': {'requiredLength': maxLength, 'actualLength': v.length}} :
null; null;
}; };
} }

View File

@ -51,11 +51,23 @@ export function main() {
}); });
describe('minLength', () => { describe('minLength', () => {
it('should not error on an empty string', it('should error on an empty string', () => {
() => { expect(Validators.minLength(2)(new FormControl(''))).toEqual(null); }); expect(Validators.minLength(2)(new FormControl(''))).toEqual({
'minlength': {'requiredLength': 2, 'actualLength': 0}
});
});
it('should not error on null', it('should error on null', () => {
() => { expect(Validators.minLength(2)(new FormControl(null))).toEqual(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', it('should not error on valid strings',
() => { expect(Validators.minLength(2)(new FormControl('aa'))).toEqual(null); }); () => { expect(Validators.minLength(2)(new FormControl('aa'))).toEqual(null); });