Carl Rippon

Building SPAs

Carl Rippon
BlogBooks / CoursesAbout
This site uses cookies. Click here to find out more

Angular Form Validation

December 23, 2015
angulartypescript

In the last post I introduced angular 2’s model driven form approach. In this post I’m going to go through how to implement validation rules on a model driven form …

Standard validators

At the moment there seem to be 3 standard validators which pretty much do what they say on the tin:

  • Validators.required
  • Validators.minLength
  • Validators.maxLength

Here’s some component code that references the standard required and minLength validators:

export class LoginComponent {
  loginForm: ControlGroup;
  constructor(builder: FormBuilder) {
    this.loginForm = builder.group({
      userName: ["", Validators.required],
      password: ["", Validators.minLength(6)]
    });
  }
}

Multiple validators

You can use Validators.compose to specify multiple validators for a field:

export class LoginComponent {
  loginForm: ControlGroup;
  constructor(builder: FormBuilder) {
    this.loginForm = builder.group({
      userName: ["", Validators.required],
      password: [
        "",
        Validators.compose([Validators.minLength(6), Validators.maxLength(12)])
      ]
    });
  }
}

Custom validation

You can reference and implement custom validation as in the following example:

export class LoginComponent {
  loginForm: ControlGroup;
  constructor(builder: FormBuilder) {
    this.loginForm = builder.group({
      userName: ["default user", Validators.required],
      password: ["", this.validateCorrectLength]
    });
  }
  validateCorrectLength(control: Control) {
    if (control.value.length < 6 || control.value.length > 8) {
      return { validPassword: false };
    } else {
      // Null means valid
      return null;
    }
  }
}

Some keypoints:

  • The validation function takes in the field Control as a parameter
  • Control.value gives the value of the field
  • The function should return null if the field is valid
  • The function should return an object if the field is invalid. This object is referenced in ControlGroup.errors when the form is in an invalid state

ControlGroup validation properties

There are some useful properties on ControlGroup (loginForm in the above examples) that can be used in validation code:

  • ControlGroup.valid is a boolean that tells us whether the form is in a valid state
  • ControlGroup.errors is null when the form is in a valid state. When the form is in an invalid state it returns an object of invalid controls
  • ControlGroup.value gives the field values

One thing I haven’t worked how to do yet is async validation …

If you to learn more about TypeScript, you may find my free TypeScript course useful:

Learn TypeScript

Learn TypeScript
Take a look

Want more content like this?

Subscribe to receive notifications on new blog posts and courses

Required
© Carl Rippon
Privacy Policy