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 26, 2018
1 parent 8fa0991 commit 408e248
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
14 changes: 12 additions & 2 deletions packages/forms/src/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,8 @@ 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 @@ -260,13 +261,22 @@ export class Validators {
*/
static maxLength(maxLength: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const length: number = control.value ? control.value.length : 0;
const length: number = (Validators.getLength(control.value));
return length > maxLength ?
{'maxlength': {'requiredLength': maxLength, 'actualLength': length}} :
null;
};
}

private static getLength(value: any): number {
if (value.hasOwnProperty('length'))
return value.length;
else if (value.__proto__.hasOwnProperty('toString')) {
return value.toString().length;
}
return 0;
}

/**
* @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 408e248

Please sign in to comment.