fix(forms): properly validate blank strings with minlength (#12091)
This commit is contained in:
parent
0254ce1f6c
commit
f50c1da4e2
|
@ -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;
|
||||
};
|
||||
}
|
||||
|
|
|
@ -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); });
|
||||
|
|
Loading…
Reference in New Issue