您好,登錄后才能下訂單哦!
在Angular中使用自定義驗證器可以通過創建一個自定義指令來實現。以下是一個簡單的示例:
import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms';
@Directive({
selector: '[appPasswordValidator]',
providers: [{provide: NG_VALIDATORS, useExisting: PasswordValidatorDirective, multi: true}]
})
export class PasswordValidatorDirective implements Validator {
@Input('appPasswordValidator') passwordPattern: string;
validate(control: AbstractControl): {[key: string]: any} | null {
const value = control.value;
const pattern = new RegExp(this.passwordPattern);
if (!pattern.test(value)) {
return { 'invalidPassword': true };
}
return null;
}
}
<input type="password" name="password" [(ngModel)]="password"
appPasswordValidator="[A-Za-z0-9]{8,}"/>
<div *ngIf="password.invalid && (password.dirty || password.touched)">
<div *ngIf="password.errors.invalidPassword">
Password must be at least 8 characters long and contain only letters and numbers.
</div>
</div>
import { PasswordValidatorDirective } from './password-validator.directive';
@NgModule({
declarations: [
PasswordValidatorDirective
]
})
export class YourModule {}
通過以上步驟,你就可以在 Angular 中使用自定義驗證器來驗證表單輸入的數據。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。