angular6 表单验证
这里使用的是模型驱动的表单
1、app.module.ts
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
...
imports: [ReactiveFormsModule, ...],
...
})
export class AppModule{
}
文件中加入了ReactiveFormsModule模块,它是使用模型驱动表单所必须的。
2、app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name: string
score: number;
formData: any;
constructor() { }
ngOnInit() {
this.formData = new FormGroup({
name: new FormControl(this.name, Validators.compose([
Validators.required,
])),
score: new FormControl(this.score, Validators.compose([
Validators.required,
this.scoreValueValidator
]))
});
}
scoreValueValidator(control: FormControl): any {
if (control.value < 0 || control.value > 100) {
return { value: {info: '分数必须大于等于0,小于等于100'} };
}
}
onsubmit(data: any) {
this.name= data.name;
this.score = data.score
}
}
表单验证,可以使用内置的表单验证,也可以使用自定义验证方法。
(1) 内置表单验证。
Validators是angular内置的验证器模块,可以使用它实现强制字段、最小长度、最大长度和模式等,我这里设置了name和score是强制字段,当然,你可以加入Validators.minLength(6), Validators.maxLength(10),Validators.pattern("[^ @]*@[^ @]*")等等。
(2) 自定义表单验证。
scoreValueValidator是自定义的验证方法,用于验证分数是否大于等于0,小于等于100,传递的参数是当前需要验证的表单的FormControl,通过control.value可以拿到输入的分数值。
3、app.component.html