Angular 10响应式表单:如何让Validators.minLength忽略空格?
Angular 10响应式表单:忽略空格的最小长度验证方案
原生的Validators.minLength(6)会把空格计入长度,没法满足忽略空格的验证需求,最简单的解决办法是自定义验证器,先去除输入内容里的所有空格,再判断剩余字符的长度是否达标。
步骤1:编写自定义验证器函数
创建一个可复用的验证器函数,接收最小长度参数,处理输入值后做长度校验:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; // 自定义验证器:忽略所有空格后检查最小长度 export function minLengthIgnoreSpaces(minLength: number): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { // 空值直接返回错误 if (!control.value) { return { minLengthIgnoreSpaces: { requiredLength: minLength, actualLength: 0 } }; } // 去除所有空格(包括中间、开头、结尾的空格) const trimmedValue = control.value.replace(/\s/g, ''); // 判断长度是否达标 return trimmedValue.length >= minLength ? null : { minLengthIgnoreSpaces: { requiredLength: minLength, actualLength: trimmedValue.length } }; }; }
步骤2:在响应式表单中使用该验证器
在组件里引入自定义验证器,和原生验证器一起配置到FormControl中:
import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; // 导入自定义验证器 import { minLengthIgnoreSpaces } from './validators'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent { form: FormGroup; constructor(private fb: FormBuilder) { this.form = this.fb.group({ targetField: ['', [ Validators.required, // 可选:如果需要必填规则的话 minLengthIgnoreSpaces(6) // 要求去除空格后至少6位 ]] }); } }
步骤3:模板中显示错误提示(可选)
在模板里根据验证结果展示对应的错误信息:
<form [formGroup]="form"> <input type="text" formControlName="targetField" placeholder="请输入内容"> <!-- 显示忽略空格后的最小长度错误 --> <div *ngIf="form.get('targetField')?.hasError('minLengthIgnoreSpaces')" style="color: red;"> 去除空格后至少需要 {{ form.get('targetField')?.errors?.minLengthIgnoreSpaces.requiredLength }} 位字符,当前实际为 {{ form.get('targetField')?.errors?.minLengthIgnoreSpaces.actualLength }} 位 </div> </form>
配置完成后,输入1234 5时,去除空格后是12345(长度5),会触发验证错误;输入1234 56时,去除空格后是123456(长度6),验证通过。
内容的提问来源于stack exchange,提问作者Juliano
相关产品推荐
相关产品推荐

