DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Henri de la Hoz
Henri de la Hoz

Posted on

Introduction to forms in Angular (Part 2)

Custom Validations

Custom validations can be achieved by creating a class that expose methods that perform the revision of a control value.

It is worth noticing that if we are working with typescript, the validation method is a static one, in other words, the method can be called without instantiating the class.

import { AbstractControl } from '@angular/forms';

export class CustomValidators {
  static isValidPrice(control: AbstractControl) {
    const value = control.value;
    if (value > 1000) {
      return { invalid_price: true };
    }
    return null;
  }
}
Enter fullscreen mode Exit fullscreen mode

AbstractControl is use to give us access to our control (what we want to validate).

One way we can use our custom validation is by adding them as elements of our validators during form groups creation.

  private buildForm() {
    this.form = this.fb.group({
      id: ['', [Validators.required]],
      title: ['', [Validators.required]],
      price: ['', [Validators.required, 
        CustomValidators.isValidPrice]],
      image: '',
      description: ['', [Validators.required]],
    });
  }
Enter fullscreen mode Exit fullscreen mode

Then we can add error messages in the view

<p *ngIf="form.get('price').hasError('invalid_price')">
    Required Price
</p>
<p *ngIf="form.get('price').hasError('required')">
    Invalid Price
</p>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. 🌈