Angular 中有两种表单:
-
Template-Driven Forms - 模板驱动式表单 (类似于 AngularJS 1.x 中的表单 )
-
Reactive Forms - 响应式表单
我们主要使用响应式表单来进行validator方法验证
首先在 @NgModule 中导入 @angular/forms 库中的 ReactiveFormsModule:
-
app.module.ts
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
...,
ReactiveFormsModule
],
declarations: [...],
bootstrap: [...]
})
export class AppModule {}
友情提示:若使用响应式表单,则导入 ReactiveFormsModule。若使用模板驱动式表单,则导入 FormsModule 。
然后创建好需要的组件:在控制台输入 ng g component 组件名 可快速创建组件并自动注册
-
在终端中创建组件$ ng g component Validator
-
在app.component.html文件中写入所创建的组件<app-validator></app-validator>
-
src\app\validator\validator.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-validator',
templateUrl: './validator.component.html',
styleUrls: ['./validator.component.css']
})
export class ValidatorComponent implements OnInit {
contactForm: FormGroup = new FormGroup({
name: new FormControl(
"",
[
Validators.required,
Validators.minLength(2)
]
})
onSubmit() {
console.log(this.contactForm.valid);
}
get name() {
return this.contactForm.get("name")
}
constructor() { }
ngOnInit(): void {
}
}
在上述例子中,name 控件设置了两个内置验证器 Validators.required 和 Validators.minLength(2)
在响应式表单中,通常会通过它所属的控件组(FormGroup)的 get 方法来访问表单控件,但有时候为模板定义一些 getter 作为简短形式。
-
src\app\validator\validator.component.html
<form [formGroup]="contactForm" (submit)="onSubmit()">
<input type="text" formControlName="name" />
<div *ngIf="name?.touched && name?.invalid && name?.errors">
<div *ngIf="name?.errors?.['required']">请填写用户名</div>
<div *ngIf="name?.errors?.['minlength']">
用户名最短2个字符
</div>
</div>
<!-- 表单整体未验证通过时禁用表单按钮 -->
<button [disabled]="contactForm.invalid">提交</button>
</form>
name?.errors控件值是否验证错误
控件状态检测,Angular会自动根据控件状态加上相应的class,如果我们需要编辑input标签在不同状态下的样式,只需要在css里写相应的类就可以了。
状态 |
true |
false |
---|---|---|
控件是否被访问过 |
touched |
untouched |
控件值是否已经变化 |
dirty |
pristine |
控件值是否有效 |
valid |
invalid |
验证器(Validator)函数
验证器函数可以是同步函数,也可以是异步函数。
-
同步验证器:这些同步函数接受一个控件实例,然后返回一组验证错误或 null。你可以在实例化一个 FormControl 时把它作为构造函数的第二个参数传进去。
-
异步验证器 :这些异步函数接受一个控件实例并返回一个 Promise 或 Observable,它稍后会发出一组验证错误或 null。在实例化 FormControl 时,可以把它们作为第三个参数传入。
自定义同步验证器
-
在app文件夹下新建myValidator.ts(文件名任意.ts)文件.
-
src\app\myValidator.ts
import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms"
export class MyValidators {
static cannotContainSpace(
control: AbstractControl
): ValidationErrors | null {
if (/\s/.test(control.value)) {
ret