在angular2中添加自定义验证器

时间:2016-11-23 14:06:22

标签: angular angular2-forms

我已经创建了自定义验证器(cannotContainSpace)并且想要使用它模板组件(postmessage.component),但不知何故验证器无法看到我创建的自定义验证器类..这里是编译器消息: enter image description here

usernamevalidator.ts

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

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

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);
    }
 }

1 个答案:

答案 0 :(得分:5)

username:['', Validators.compose([Validators.required, Validators.cannotContainSpace])],   

应该是

username:['', Validators.compose([Validators.required, UsernameValidator.cannotContainSpace])],   

Validators类仅提供Validators类中定义的验证器。