我有多个输入字段,需要几乎相同的验证。有什么方法可以减少显示错误的重复 HTML 代码。
我的代码如下
<div colspan="2">
<input type="text" name="appName" [disabled]="recordCreated" [(ngModel)]="appName" appForbiddenName="Application" minlength="4"
required #name="ngModel" [ngClass]="{'has-danger': name.invalid && (name.dirty || name.touched) }" />
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
<div *ngIf="name.errors.forbiddenName">
Name cannot be Application.
</div>
</div>
</div>
<div colspan="2">
<input type="text" name="appName" [disabled]="recordCreated" [(ngModel)]="desc" appForbiddenName="Application" minlength="4"
required #desc="ngModel" [ngClass]="{'has-danger': desc.invalid && (desc.dirty || desc.touched) }" />
<div *ngIf="desc.invalid && (desc.dirty || desc.touched)" class="alert alert-danger">
<div *ngIf="desc.errors.required">
Desc is required.
</div>
<div *ngIf="desc.errors.minlength">
Desc must be at least 4 characters long.
</div>
<div *ngIf="desc.errors.forbiddenName">
Desc cannot be Application.
</div>
</div>
</div>
import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, ValidatorFn } from '@angular/forms';
import { AbstractControl } from '@angular/forms/src/model';
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl) : {[key: string] : any} | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? {'forbiddenName': {value: control.value}} : null;
};
}
@Directive({
selector: '[appForbiddenName]',
providers: [{ provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true }]
})
export class ForbiddenValidatorDirective implements Validator {
@Input('appForbiddenName') forbiddenName: string;
validate(control: AbstractControl): { [key: string]: any } | null {
return this.forbiddenName ? forbiddenNameValidator(new RegExp
(this.forbiddenName, 'i'))(control) : null;
}
}
除了输入字段和强制 div 标记外,所有其他验证器 html 代码都针对每个输入字段重复。有没有办法可以在指令中返回错误消息模板。而不仅仅是空