使用内置验证器提供的验证规则验证表单字段

  1. import { FormControl, FormGroup, Validators } from "@angular/forms"
  2. contactForm: FormGroup = new FormGroup({
  3. name: new FormControl("默认值", [
  4. Validators.required,
  5. Validators.minLength(2)
  6. ])
  7. })

获取整体表单是否验证通过

  1. onSubmit() {
  2. console.log(this.contactForm.valid)
  3. }
  1. <form [formGroup]="contactForm" (submit)="onSubmit()">
  2. <input type="text" formControlName="name" />
  3. <button [disabled]="contactForm.invalid">提交</button>
  4. </form>

在组件模板中显示为验证通过时的错误信息

  1. // 获取到 contactForm 下的 FormControl 实例化对象 name
  2. get name() {
  3. return this.contactForm.get("name")!
  4. }
  1. <form [formGroup]="contactForm" (submit)="onSubmit()">
  2. <input type="text" formControlName="name" />
  3. <div *ngIf="name.touched && name.invalid && name.errors">
  4. <div *ngIf="name.errors?.['required']">请填写姓名</div>
  5. <div *ngIf="name.errors?.['maxlength']">
  6. 姓名长度不能大于
  7. {{ name.errors?.['maxlength'].requiredLength }} 实际填写长度为
  8. {{ name.errors?.['maxlength'].actualLength }}
  9. </div>
  10. </div>
  11. <button [disabled]="contactForm.invalid">提交</button>
  12. </form>