Validators.minLength(6)除了忽略空格之外,有什么解決方案可以使用嗎?
EG:1234 5這會驗證,但它不應該,因為我希望驗證沒有空格的 6 位數字 EG:1234 56
謝謝。
uj5u.com熱心網友回復:
當我搜索特定的 Angular 時,我找不到任何答案,在搜索更通用的內容后,html minlength validation digits without spaces我發現了一些可以讓我找到解決方案的東西。ref: html 輸入模式
這是我們也可以在角度中使用的 html 輸入模式屬性,所以我的解決方案是:
Validators.pattern('\\s*(\\S\\s*){16,}')
以上對我來說真的很好!
uj5u.com熱心網友回復:
雖然您的模式方法有效,但它幾乎不具有“可讀性”。在這種情況下,我建議您查看Custom Validators。
類似以下的內容應該是您正在尋找的內容。
export function maxPrunedLength(length: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const prunedValueLength = control.value.replaceAll(' ','').length;
return prunedValueLength > length
? {forbiddenName: {value: control.value}}
: null;
};
}
uj5u.com熱心網友回復:
那沒有。Validators.minLength(6)是一個工廠,它創建一個函式,該函式接受一個 FormControl 并回傳一個錯誤物件或 null - 也稱為 ValidatorFn。您可以通過更改提供的控制元件來使用它。
export class CustomValidators {
static minLengthIgnoreWhitespace(length: number): ValidatorFn {
return (control: AbstractControl) => {
const modifiedControl: FormControl = new FormControl(control.value.replace(/\s/g, ''));
return Validators.minLength(length)(modifiedControl);
};
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522006.html
標籤:有角度的角度验证器
