Validating FormBuilder Forms

Building from the previous login form, we can quickly and easily add validation.

Angular provides many validators out of the box. They can be imported along with the rest of dependencies for procedural forms.


import { Component } from '@angular/core';
import { Validators, FormBuilder, FormControl } from '@angular/forms';

  // ...
export class AppComponent {
  username = new FormControl('', [

  password = new FormControl('', [Validators.required]);

  loginForm: FormGroup ={
    username: this.username,
    password: this.password

  constructor(private builder: FormBuilder) { }

  login () {
    // Attempt Logging in...


<form [formGroup]="loginForm" (ngSubmit)="login()">

    <label for="username">username</label>


    <div [hidden]="username.valid || username.untouched">
        The following problems have been found with the username:

      <div [hidden]="!username.hasError('minlength')">
        Username can not be shorter than 5 characters.
      <div [hidden]="!username.hasError('required')">
        Username is required.
  <div >
    <label for="password">password</label>
      id="password" [formControl]="password">

    <div [hidden]="password.valid || password.untouched">
        The following problems have been found with the password:

      <div [hidden]="!password.hasError('required')">
        The password is required.

  <button type="submit" [disabled]="!loginForm.valid">Log In</button>

Note that we have added rather robust validation on both the fields and the form itself, using nothing more than built-in validators and some template logic.

View Example

We are using .valid and .untouched to determine if we need to show errors - while the field is required, there is no reason to tell the user that the value is wrong if the field hasn't been visited yet.

For built-in validation, we are calling .hasError() on the form element, and we are passing a string which represents the validator function we included. The error message only displays if this test returns true.

Last updated