要忽略空格,可以自定义验证器,将输入值与修剪后的输入值进行比较。以下是一个示例:
import { AbstractControl, ValidatorFn } from '@angular/forms';
export function minLengthValidator(minLength: number): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
const inputTrimmed = (control.value || '').trim(); // 修剪输入值
const isValidLength = inputTrimmed.length >= minLength;
return isValidLength ? null : { 'minLength': { 'requiredLength': minLength } };
};
}
然后,可以在表单控件定义中使用自定义验证器:
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { minLengthValidator } from './min-length-validator';
@Component({
selector: 'app-root',
template: `
`,
})
export class AppComponent {
readonly minLength = 3;
readonly form = new FormGroup({
name: new FormControl('', [minLengthValidator(this.minLength)]),
});
}