Skip to content

Commit 140e7c0

Browse files
pmccloghrylaingmhevery
authored andcommitted
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
1 parent 941e88f commit 140e7c0

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

packages/forms/src/validators.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,9 @@ export class Validators {
125125
* Validator that performs email validation.
126126
*/
127127
static email(control: AbstractControl): ValidationErrors|null {
128+
if (isEmptyInputValue(control.value)) {
129+
return null; // don't validate empty values to allow optional controls
130+
}
128131
return EMAIL_REGEXP.test(control.value) ? null : {'email': true};
129132
}
130133

packages/forms/test/template_integration_spec.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1265,6 +1265,13 @@ import {NgModelCustomComp, NgModelCustomWrapper} from './value_accessor_integrat
12651265
tick();
12661266

12671267
expect(input.nativeElement.value).toEqual('');
1268+
expect(control.hasError('email')).toBe(false);
1269+
1270+
input.nativeElement.value = '@';
1271+
dispatchEvent(input.nativeElement, 'input');
1272+
tick();
1273+
1274+
expect(input.nativeElement.value).toEqual('@');
12681275
expect(control.hasError('email')).toBe(true);
12691276

12701277
input.nativeElement.value = 'test@gmail.com';

packages/forms/test/validators_spec.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,12 @@ import {map} from 'rxjs/operator/map';
159159
});
160160

161161
describe('email', () => {
162+
it('should not error on an empty string',
163+
() => expect(Validators.email(new FormControl(''))).toBeNull());
164+
165+
it('should not error on null',
166+
() => expect(Validators.email(new FormControl(null))).toBeNull());
167+
162168
it('should error on invalid email',
163169
() => expect(Validators.email(new FormControl('some text'))).toEqual({'email': true}));
164170

0 commit comments

Comments
 (0)