在angular2中添加自定义验证器

TyF*_*ude 2 angular2-forms angular

我已经创建了自定义验证器(cannotContainSpace)并想要使用它模板组件(postmessage.component),但不知何故验证器无法看到我创建的自定义验证器类..这里是编译器消息: 在此输入图像描述

usernamevalidator.ts

import {FormControl} from '@angular/forms';

export class UsernameValidator{
    static cannotContainSpace(control:FormControl){
        if(control.value.indexOf('')>=0)
            return {    cannotContainSpace:true };
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

postmessage.component.ts

import { Component } from '@angular/core';
import {FormControl,FormGroup,FormBuilder,Validators} from '@angular/forms';
import {UsernameValidator} from '../../validators/usernamevalidator';

@Component({
    moduleId:module.id,
    selector: 'post-message',
    templateUrl: '../../templates/postmessage.component.html'
})
export class PostComponent {
    form : FormGroup;
    constructor(fb:FormBuilder){
        this.form = fb.group({
            username:['', Validators.compose([Validators.required, Validators.cannotContainSpace])],            
            email:['', Validators.required],         
            message:['', Validators.required]         
        });
    }
    signup(){
        console.log(this.form.value);
    }
 }
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

username:['', Validators.compose([Validators.required, Validators.cannotContainSpace])],   
Run Code Online (Sandbox Code Playgroud)

应该

username:['', Validators.compose([Validators.required, UsernameValidator.cannotContainSpace])],   
Run Code Online (Sandbox Code Playgroud)

Validators类只提供在中定义的验证Validators类.