MST

星途 面试题库

面试题:Angular表单验证之基础规则实现

在Angular项目中,假设你有一个包含用户名和密码的表单。用户名要求至少3个字符且只能包含字母和数字,密码要求至少6个字符且必须包含至少一个数字。请描述如何使用Angular的内置验证器以及自定义验证器来实现这些表单验证逻辑,并给出关键代码片段。
32.1万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 使用Angular内置验证器

    • 在模板驱动表单中,可直接在<input>元素上使用验证器指令。
    • 在响应式表单中,在创建表单控件时传入验证器。

    用户名验证

    • 模板驱动表单:
    <input type="text" name="username" [(ngModel)]="user.username" required minlength="3" pattern="[a-zA-Z0-9]{3,}">
    
    • 响应式表单:
    import { FormControl, Validators } from '@angular/forms';
    
    const usernameControl = new FormControl('', [
      Validators.required,
      Validators.minLength(3),
      Validators.pattern('[a-zA-Z0-9]{3,}')
    ]);
    

    密码验证

    • 模板驱动表单:
    <input type="password" name="password" [(ngModel)]="user.password" required minlength="6" pattern="^(?=.*\d).{6,}$">
    
    • 响应式表单:
    const passwordControl = new FormControl('', [
      Validators.required,
      Validators.minLength(6),
      Validators.pattern('^(?=.*\d).{6,}$')
    ]);
    
  2. 自定义验证器

    • 若内置验证器无法满足复杂需求,可创建自定义验证器。例如,创建一个验证密码强度的自定义验证器,要求密码必须包含数字。
    • 首先创建自定义验证器函数:
    import { AbstractControl } from '@angular/forms';
    
    export function passwordContainsDigitValidator(control: AbstractControl): { [key: string]: any } | null {
      const hasDigit = /\d/.test(control.value);
      return hasDigit? null : { passwordNoDigit: true };
    }
    
    • 然后在响应式表单中使用:
    const passwordControl = new FormControl('', [
      Validators.required,
      Validators.minLength(6),
      passwordContainsDigitValidator
    ]);
    
    • 在模板驱动表单中使用自定义验证器会更复杂,通常需要借助Directive来实现,以下是简单示例:
    import { Directive, forwardRef } from '@angular/core';
    import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms';
    
    @Directive({
      selector: '[appPasswordContainsDigit]',
      providers: [
        { provide: NG_VALIDATORS, useExisting: forwardRef(() => PasswordContainsDigitDirective), multi: true }
      ]
    })
    export class PasswordContainsDigitDirective implements Validator {
      validate(control: AbstractControl): { [key: string]: any } | null {
        const hasDigit = /\d/.test(control.value);
        return hasDigit? null : { passwordNoDigit: true };
      }
    }
    
    • 模板中使用:
    <input type="password" name="password" [(ngModel)]="user.password" required minlength="6" appPasswordContainsDigit>