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

<div class="container">
  <form [formGroup] = "formData" (ngSubmit) = "onsubmit(formData.value)">
    <div class="form-group">
      <label for="name">姓名</label>
      <em>*</em>
      <input type="text" class="form-control" formControlName="name" >
      <div [hidden]="formData.get('name').valid || formData.get('name').untouched" class="small">
        <p [hidden]="!formData.hasError('required', 'threshold')">必填项</p>
      </div>
    </div>
    <div class="form-group">
      <label for="score">分数</label>
      <em>*</em>
      <input type="number" min="0" max="100" class="form-control" formControlName="score" >
      <div [hidden]="formData.get('score').valid || formData.get('score').untouched" class="small">
        <p [hidden]="!formData.hasError('required', 'score')">必填项</p>
        <p [hidden]="!formData.hasError('value', 'score')">{{formData.getError('value', 'score')?.info}}</p>
      </div>
    <button type="submit" [disabled]="!formData.valid" class="btn btn-sm btn-primary">提交</button>
  </form>
</div>

页面中显示错误信息

对于提交按钮,我们已经在方括号中添加了disabled,它被赋予值 !formData.valid。因此,如果formData.valid无效,按钮将保持禁用状态,用户将无法提交它。

4、app.component.css

em {
    color:red;
    margin-left: 0.25em
}
.ng-touched:not(form),.ng-invalid:not(form) {
    border: 1px solid #f00;
}
.ng-valid:not(form),.ng-untouched:not(form) {
    border: 1px solid #ddd;
}
p{
    color:#f00;
}