[英]Restrict special characters in angular reactive forms using custom validators
我想使用自定義驗證器限制角度反應形式中的特殊字符。 我在堆棧溢出中進行了搜索,但沒有按預期工作。
HTML.TS
<input matInput placeholder="no symbols" formControlName="symbols" [errorStateMatcher]="matcher">
<mat-error *ngIf="signupForm.controls['symbols'].hasError('symbols')">
symbols are not allowed
</mat-error>
CUSTOM VALIDATOR.TS
export function symbolsOnly(control: AbstractControl) {
if ( /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./]*$/.test(control.value)) {
return { symbols: true };
}
return null;
}
COMPONENT.TS
'symbols':new FormControl("",[symbolsOnly])
有人可以幫助我了解如何使用自定義驗證器限制角度反應形式中的特殊字符
這是您的示例,它執行特殊字符驗證
symbols: ["", Validators.compose([Validators.pattern("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9 !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~€£¥₩])(?=.*?[A-Z 0-9]).{8,}$"), Validators.required])],
您在有效狀態下返回錯誤,試試這個
export function symbolsOnly(control: AbstractControl) {
if ( !/^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./]*$/.test(control.value)) {
return { symbols: true };
}
return null;
}
在 component.ts
//Validates that the field only contains letters or digits, you can modify the regex accordingly
const symbols = new FormControl('', Validators.pattern('[a-zA-Z0-9]*'));
console.log(symbols.errors); // {pattern: {requiredPattern: '^[a-zA-Z0-9]*$',actualValue: ''}}
您的方式是儀式,但您應該使用ValidatorFn
接口為反應式formControl
返回錯誤映射。
組件中的反應形式字段。
field1 : new FormControl('', forbiddenStringValidator(regex))
為自定義驗證和客戶驗證器創建單獨的文件
export function forbiddenStringValidator(stringRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
const forbidden = stringRe.test(control.value);
return forbidden ? {'forbiddenString': {value: control.value}} : null;
};
【注意】:REGEX應根據要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.