📜  angular9+how+to+add+validators (1)

📅  最后修改于: 2023-12-03 14:59:18.753000             🧑  作者: Mango

Angular 9: How to Add Validators

Angular 9 is the latest version of the popular front-end JavaScript framework. One of the most important features of Angular 9 is its ability to add validators to forms. Validators allow you to validate user input, ensuring that only valid input is accepted. In this tutorial, we will explore how to add validators in Angular 9.

Setup

Before we get started, make sure you have the following:

  • Node.js and npm installed on your machine
  • Angular CLI installed globally (npm install -g @angular/cli)
  • A basic Angular 9 project setup (ng new my-project)
Adding Validators

Validators in Angular 9 are added to form controls. A form control is an object that represents an input field on a form. To add a validator to a form control, you need to create a validator function and pass it to the control.

Here's an example of how to add a required validator to a form control:

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

@Component({
  selector: 'my-app',
  template: `
    <form>
      <input type="text" [formControl]="myControl">
    </form>
  `
})
export class AppComponent {
  myControl = new FormControl('', Validators.required);
}

In the example above, we import the FormControl and Validators classes from @angular/forms. We then create a new form control called myControl and pass it an empty string as the initial value and a required validator.

Built-in Validators

Angular 9 comes with a number of built-in validators that you can use out of the box. Here are some of the most commonly used validators:

  • required: Makes the control required.
  • minLength: Makes the control require a minimum length.
  • maxLength: Makes the control require a maximum length.
  • pattern: Makes the control require a specific pattern.
  • email: Makes the control require a valid email.

Here's an example of how to use the minLength validator:

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

@Component({
  selector: 'my-app',
  template: `
    <form>
      <input type="text" [formControl]="myControl">
    </form>
  `
})
export class AppComponent {
  myControl = new FormControl('', Validators.minLength(3));
}

In the example above, we pass the minLength validator to myControl. This makes the control require a minimum length of 3 characters.

Conclusion

Validators are an important part of building forms in Angular 9. They allow you to ensure that user input is valid and prevent invalid data from being submitted. In this tutorial, we explored how to add validators to form controls in Angular 9. We also looked at some of the built-in validators that come with Angular 9.