2016-07-29 102 views
3

我写了一个自定义的验证指令那样:不叫Angular2自定义验证

const DURATION_VALIDATOR = new Provider(
    NG_VALIDATORS, 
    {useExisting: forwardRef(() => DurationDirective), multi: true} 
); 


@Directive({ 
    selector: '[ngModel][duration], [formControl][duration]', 
    providers: [{ 
     provide: NG_VALIDATORS, 
     useExisting: forwardRef(() => DurationDirective), 
     multi: true }] 
}) 
export class DurationDirective implements Validator{ 
    constructor(public model:NgModel){ 
     console.error('init') 
    } 
    validate(c:FormControl) { 
     console.error('validate') 
     return {'err...':'err...'}; 
    } 
} 

我的HTML看起来像这样:

<input 
    type="text" 
    [(ngModel)]="preparation.duration" 
    duration 
    required 
> 

我的问题是,虽然验证被初始化,即' init'被记录到控制台,验证函数永远不会被调用,即在输入字段中输入时,“验证”从不记录到控制台。由于验证程序已初始化,因此我假设我“正确”连接了所有内容。那么缺少什么?

回答

0

我的最好的办法是,你有没有bootstraped角与问候形式:

import { App } from './app'; 
import { disableDeprecatedForms, provideForms } from '@angular/forms'; 

bootstrap(App, [ 
    // these are crucial 
    disableDeprecatedForms(), 
    provideForms() 
    ]); 

你可以看到这个plunk - 它输出"validate"到控制台。

+0

我已将disableDeprecatedForms(),provideForms()添加到我的组件提供程序属性中。但这似乎没有任何影响。你能解释为什么吗?这是我更新的plunk https://plnkr.co/edit/ztuBIZc3QMRwMg62scZR?p=preview – schacki

+0

这个plunk仍然没有在bootstrap()调用中提供两个调用。将您在提供者属性中的两个调用移动到引导方法可以解决问题。 https://plnkr.co/edit/b2PipR?p=preview – batesiiic

+0

对不起,这是一个误解。我故意将提供的调用从引导方法转移到my-app组件来说明我的问题:我的假设是将2个调用添加到组件提供程序中就足够了。你能解释为什么不能? – schacki

0

我分叉的和改进的@batesiiic的普拉克:https://plnkr.co/edit/Vokcid?p=preview

validate(c:FormControl) { 
    console.error('called validate()') 
    return parseInt(c.value) < 10 ? null : { 
     duration: {message: 'Please enter a number < 10'} 
    }; 
} 

的validate()方法必须返回null如果输入是有效的,否则,它返回一个对象{键:值,... }其中key是错误的类型,值可以是任何可以在模板中用来生成错误消息的值。

如果输入无效,模板还包含一个div以显示错误消息。

0

而不是将自定义验证器函数编写为类/组件/指令方法, 在组件/指令之外编写自定义验证器应该可行。

validate(c:FormControl) { 
    console.error('validate') 
    return {'err...':'err...'}; 
} 

@Directive({ 
    selector: '[ngModel][duration], [formControl][duration]', 
    providers: [{ 
     provide: NG_VALIDATORS, 
     useExisting: forwardRef(() => DurationDirective), 
     multi: true }] 
}) 
export class DurationDirective implements Validator{ 
    constructor(public model:NgModel){ 
     console.error('init') 
    } 

}