Skip to content

Commit

Permalink
fix(forms): make Validators.email support optional controls (angular#…
Browse files Browse the repository at this point in the history
…20869)

Bring email validator in line with other validators so that empty values are ignored.

PR Close angular#20869
  • Loading branch information
pmccloghrylaing authored and jbogarthyde committed Feb 23, 2018
1 parent d3a8218 commit 86ca527
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/forms/src/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ export class Validators {
* Validator that performs email validation.
*/
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};
}

Expand Down
7 changes: 7 additions & 0 deletions packages/forms/test/template_integration_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1265,6 +1265,13 @@ import {NgModelCustomComp, NgModelCustomWrapper} from './value_accessor_integrat
tick();

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);

input.nativeElement.value = 'test@gmail.com';
Expand Down
6 changes: 6 additions & 0 deletions packages/forms/test/validators_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,12 @@ import {map} from 'rxjs/operator/map';
});

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',
() => expect(Validators.email(new FormControl('some text'))).toEqual({'email': true}));

Expand Down

0 comments on commit 86ca527

Please sign in to comment.