Skip to content

Commit

Permalink
fix(forms): properly validate blank strings with minlength (#12091)
Browse files Browse the repository at this point in the history
  • Loading branch information
pkozlowski-opensource authored and tbosch committed Oct 6, 2016
1 parent 0254ce1 commit f50c1da
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 12 deletions.
14 changes: 6 additions & 8 deletions modules/@angular/forms/src/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
}
Expand All @@ -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;
};
}
Expand Down
20 changes: 16 additions & 4 deletions modules/@angular/forms/test/validators_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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); });
Expand Down

0 comments on commit f50c1da

Please sign in to comment.