Skip to content

Commit

Permalink
fix(forms): minLength validator treats zero value as zero length (ang…
Browse files Browse the repository at this point in the history
  • Loading branch information
csmehta committed Aug 28, 2018
1 parent 0024d68 commit 4bb8241
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/forms/src/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ export class Validators {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
const length: number = control.value ? control.value.length : 0;
const length: number = (Validators.getLength(control.value));
return length < minLength ?
{'minlength': {'requiredLength': minLength, 'actualLength': length}} :
null;
Expand Down Expand Up @@ -267,6 +267,10 @@ export class Validators {
};
}

private static getLength(value: any): number {
return (value.length || (value.length == 0)) ? value.length : value.toString().length;
}

/**
* @description
* Validator that requires the control's value to match a regex pattern. This validator is also
Expand Down
9 changes: 9 additions & 0 deletions packages/forms/test/validators_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,15 @@ import {first, map} from 'rxjs/operators';
});
});

it('should not error when valid strings is the number 0',
() => { expect(Validators.minLength(1)(new FormControl(0))).toBeNull(); });

it('should error on short strings with value as the number 0', () => {
expect(Validators.minLength(2)(new FormControl(0))).toEqual({
'minlength': {'requiredLength': 2, 'actualLength': 1}
});
});

it('should not error when FormArray has valid length', () => {
const fa = new FormArray([new FormControl(''), new FormControl('')]);
expect(Validators.minLength(2)(fa)).toBeNull();
Expand Down

0 comments on commit 4bb8241

Please sign in to comment.