fix(forms): make Validators.email support optional controls (#20869)
Bring email validator in line with other validators so that empty values are ignored. PR Close #20869
This commit is contained in:
parent
941e88ff79
commit
140e7c00d1
@ -125,6 +125,9 @@ export class Validators {
|
|||||||
* Validator that performs email validation.
|
* Validator that performs email validation.
|
||||||
*/
|
*/
|
||||||
static email(control: AbstractControl): ValidationErrors|null {
|
static email(control: AbstractControl): ValidationErrors|null {
|
||||||
|
if (isEmptyInputValue(control.value)) {
|
||||||
|
return null; // don't validate empty values to allow optional controls
|
||||||
|
}
|
||||||
return EMAIL_REGEXP.test(control.value) ? null : {'email': true};
|
return EMAIL_REGEXP.test(control.value) ? null : {'email': true};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1265,6 +1265,13 @@ import {NgModelCustomComp, NgModelCustomWrapper} from './value_accessor_integrat
|
|||||||
tick();
|
tick();
|
||||||
|
|
||||||
expect(input.nativeElement.value).toEqual('');
|
expect(input.nativeElement.value).toEqual('');
|
||||||
|
expect(control.hasError('email')).toBe(false);
|
||||||
|
|
||||||
|
input.nativeElement.value = '@';
|
||||||
|
dispatchEvent(input.nativeElement, 'input');
|
||||||
|
tick();
|
||||||
|
|
||||||
|
expect(input.nativeElement.value).toEqual('@');
|
||||||
expect(control.hasError('email')).toBe(true);
|
expect(control.hasError('email')).toBe(true);
|
||||||
|
|
||||||
input.nativeElement.value = 'test@gmail.com';
|
input.nativeElement.value = 'test@gmail.com';
|
||||||
|
@ -159,6 +159,12 @@ import {map} from 'rxjs/operator/map';
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('email', () => {
|
describe('email', () => {
|
||||||
|
it('should not error on an empty string',
|
||||||
|
() => expect(Validators.email(new FormControl(''))).toBeNull());
|
||||||
|
|
||||||
|
it('should not error on null',
|
||||||
|
() => expect(Validators.email(new FormControl(null))).toBeNull());
|
||||||
|
|
||||||
it('should error on invalid email',
|
it('should error on invalid email',
|
||||||
() => expect(Validators.email(new FormControl('some text'))).toEqual({'email': true}));
|
() => expect(Validators.email(new FormControl('some text'))).toEqual({'email': true}));
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user