Skip to content

Latest commit

 

History

History
31 lines (24 loc) · 2.1 KB

exercise-4_create-custom-async-validator-directive.md

File metadata and controls

31 lines (24 loc) · 2.1 KB

Exercise: Create async validator directive

In this exercise we'll explore how async validators are implemented in Angular 2. We'll learn how to create a validator that has service dependencies and how it needs to be added to the NG_ASYNC_VALIDATORS providers.

Scenario

Email addresses should be unique. We shouldn't have multiple contacts that share the same email address. That's why we want make sure that, when a contact is added, the email address (if applied) isn't already used in an existing contact.

Tasks

  1. Add a method isEmailAvailable(email) to ContactsService
  • Use http.get() to send a request to {API-ENDPOINT}/check-email?email={EMAIL}
  • This endpoint returns
    • { error: 'NOT_AVAILABLE' } - in case the given email address is in use
    • { msg: 'AVAILABLE' } - in case the email address is available
  1. Create a directive using angular-cli called email-availability-validator
  2. Add a validator factory function checkEmailAvailability(contactsService: ContactsService) to src/app/email-availability-validator.ts.
  3. Return the observable of ContactsService#isEmailAvailable(), make sure that it projects/emits the right next value, which is:
  • null - if the email address is available or,
  • { emailTaken: true } - if the email address is not available
  1. Inject ContactsService into EmailAvailabilityValidator
  2. Use checkEmailAvailability() as a factory function to store a validator on the class
  3. Implement a method validate(c: FormControl) on EmailAvailabilityValidator which uses the new validator
  4. Change EmailAvailabilityValidator's selector to [trmCheckEmailAvailability][ngModel].
  5. Add the validator to NG_ASYNC_VALIDATORS using forwardRef and useExisting when configuring the provider
  6. Apply trmCheckEmailAvailability directive to email input in ContactCreatorComponents template
  7. Display an error message accordingly

Next Lab

Go to Forms Lab #5: Refactor to Reactive Forms