Common validations

Before we move on, we need to implement validations for loginForm. As we implement more forms in Chapter 10, Angular App Design and Recipes, you will realize that it gets tedious, fast, to repeatedly type out form validations in either template or reactive forms. Part of the allure of reactive forms is that it is driven by code, so we can easily extract out the validations to a shared class, unit test, and reuse them:

  1. Create a validations.ts file under the common folder
  2. Implement email and password validations:
src/app/common/validations.ts
import { Validators } from '@angular/forms'

export const EmailValidation = [Validators.required, Validators.email]
export const PasswordValidation = [
Validators.required,
Validators.minLength(8),
Validators.maxLength(50),
]
Depending on your password validation needs, you can use a RegEx pattern with the Validations.pattern() function to enforce password complexity rules or leverage the OWASP npm package, owasp-password-strength-test, to enable pass-phrases as well as set more flexible password requirements.
  1. Update the login component with the new validations:
src/app/login/login.component.ts
import { EmailValidation, PasswordValidation } from '../common/validations'
...
this.loginForm = this.formBuilder.group({
email: ['', EmailValidation],
password: ['', PasswordValidation],
})
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.23.147