在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。