我一直在检查表单验证基础知识 at the official docs我无法理解其中一个例子。
一些背景:
In this sample, the forbidden name is "bob", so the validator will reject any hero name containing "bob". Elsewhere it could reject "alice" or any name that the configuring regular expression matches.
这是输入元素:
<input id="name" name="name" class="form-control"
required minlength="4" forbiddenName="bob"
[(ngModel)]="hero.name" #name="ngModel" >
然而,他们示例中的输入似乎未经过验证:
虽然来自同一示例的使用响应式(Reactive)形式的输入按预期得到验证:
如何使模板驱动的表单以 react 形式显示警报?
这是来自官方文档的示例:https://stackblitz.com/angular/byyynkdrode
提前致谢!
最佳答案
必须是
<input id="name" name="name" class="form-control"
required minlength="4" appForbiddenName forbiddenName="bob"
[(ngModel)]="hero.name" #name="ngModel" >
或
<input id="name" name="name" class="form-control"
required minlength="4" appForbiddenName [forbiddenName]="'bob'"
[(ngModel)]="hero.name" #name="ngModel" >
看到指令名称是“appForbiddenName”,@Input 变量是“forbiddenName”。当然,您可以更改指令,并使选择器的名称与@Input 相同
@Directive({
selector: '[forbiddenName]', //<--forbiddenName, NOT appforbiddenName
providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
})
export class ForbiddenValidatorDirective implements Validator {
@Input() forbiddenName: string; //<--see that the input variable is the same
//that the selector of the directive
....
}
关于使用指令的 Angular 模板驱动的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547947/