Jupyter AI

20 表单处理之表单验证

📅 发表日期: 2024年8月15日

分类: 🅰️Angular 入门

👁️阅读: --

在本章中,我们将深入了解 Angular 中的表单验证。表单验证是确保用户输入的数据有效且符合预期的重要步骤。正确的表单验证可以提高用户体验,帮助用户及时获取输入错误的信息,并且避免无效数据的提交。

表单验证的基础

Angular 中的表单验证可以通过响应式表单和模板驱动表单两种方式来实现。在上一章中,我们探讨了响应式和模板驱动表单的创建和使用方式。接下来,我们将重点关注如何在这些表单中实现有效的验证规则。

常见的验证器

Angular 提供了一些内置的验证器,您可以在表单控件中使用它们。以下是一些常见的验证器:

  • required:确保字段不为空。
  • minlength:验证输入的字符串最少字符长度。
  • maxlength:验证输入的字符串最多字符长度。
  • pattern:验证输入内容是否符合正则表达式模式。
  • email:验证输入内容是否符合电子邮件格式。

使用内置验证器的案例

这里我们将使用一个简单的示例,演示如何在响应式表单中使用这些内置验证器。

首先,在组件中设置表单:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html'
})
export class RegistrationComponent implements OnInit {
  registrationForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.registrationForm = this.fb.group({
      username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(15)]],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]]
    });
  }

  onSubmit(): void {
    if (this.registrationForm.valid) {
      console.log(this.registrationForm.value);
    } else {
      console.error('Form is invalid');
    }
  }
}

在这个示例中,我们创建了一个名为 registrationForm 的表单,包含 usernameemailpassword 三个字段。每个字段都附加了不同的验证器,用于检测输入的有效性。

在模板中显示验证状态

接下来,我们需要在模板中显示验证状态,以便用户了解输入的有效性。以下是对应的 HTML 模板内容:

<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="username">Username:</label>
    <input id="username" formControlName="username" />
    <div *ngIf="registrationForm.get('username').invalid && (registrationForm.get('username').touched || registrationForm.get('username').dirty)">
      <small *ngIf="registrationForm.get('username').errors?.required">Username is required.</small>
      <small *ngIf="registrationForm.get('username').errors?.minlength">Username must be at least 3 characters long.</small>
      <small *ngIf="registrationForm.get('username').errors?.maxlength">Username cannot exceed 15 characters.</small>
    </div>
  </div>

  <div>
    <label for="email">Email:</label>
    <input id="email" formControlName="email" />
    <div *ngIf="registrationForm.get('email').invalid && (registrationForm.get('email').touched || registrationForm.get('email').dirty)">
      <small *ngIf="registrationForm.get('email').errors?.required">Email is required.</small>
      <small *ngIf="registrationForm.get('email').errors?.email">Invalid email format.</small>
    </div>
  </div>

  <div>
    <label for="password">Password:</label>
    <input id="password" formControlName="password" type="password" />
    <div *ngIf="registrationForm.get('password').invalid && (registrationForm.get('password').touched || registrationForm.get('password').dirty)">
      <small *ngIf="registrationForm.get('password').errors?.required">Password is required.</small>
      <small *ngIf="registrationForm.get('password').errors?.minlength">Password must be at least 6 characters long.</small>
    </div>
  </div>

  <button type="submit">Register</button>
</form>

在模板中,我们使用了 *ngIf 指令来根据表单控件的状态条件显示错误消息。toucheddirty 属性有助于确保只有在用户与输入字段交互后才显示错误信息。

自定义验证器

除了 Angular 提供的内置验证器之外,您还可以创建自定义验证器来实现更复杂的验证逻辑。

创建自定义验证器示例

以下是一个简单的自定义验证器示例,它确保输入的值是一个特定的字符串:

import { AbstractControl, ValidatorFn } from '@angular/forms';

export function customValidator(expectedValue: string): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const forbidden = control.value !== expectedValue;
    return forbidden ? { 'customError': { value: control.value } } : null;
  };
}

您可以在表单控件中使用这个自定义验证器:

this.registrationForm = this.fb.group({
  username: ['', [Validators.required, customValidator('admin')]],
  // 其他字段...
});

结论

在本章中,我们学习了如何在 Angular 中实现表单验证,无论是使用内置的验证器还是自定义的验证逻辑。有效的表单验证不仅可以增强用户体验,还可以确保收集到的数据是有效的。

接下来,我们将进入表单控件的相关内容,探索如何在 Angular 中处理表单控件及其状态。