TyForHelpDude
TyForHelpDude

Reputation: 5001

adding custom validators in angular2

I have created custom validator(cannotContainSpace) and want to use it template component(postmessage.component) but somehow validator cant see my custom validator class I've created.. here is the compiler message: 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);
    }
 }

Upvotes: 2

Views: 5535

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658017

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

should be

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

The Validators class only provides validators that are defined in the Validators class.

Upvotes: 5

Related Questions