I get the error 'Expected validator to return Promise or Observable' while trying to implement an custom synchronous validator. I am using the FormControl and FormGroup classes for bulding the validators.
This change from beta to final release is confusing. Kindly help me out.
Thanks in Advance
Please find below my code for the same:
userNameValidator.ts
import { FormControl } from '@angular2/common';
export class UserNameValidator
{
static cannotContainSpaces(control:Control)
{
const username = control.value;
console.log(username + "here")
console.log( username.indexOf(' ')>=0 ? {'containsSpace':true} : null);
return username.indexOf(' ')>=0 ? {'containsSpace':true} : null;
}
}
signup.component.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder} from '@angular/forms';
import { UserNameValidator } from './userNameValidator';
@Component({
selector: 'my-app',
templateUrl: './signup.component.html'
})
export class SignupComponent
{
form: FormGroup;
constructor(fb: FormBuilder)
{
this.form = fb.group({
username:
[null,Validators.compose([Validators.required,Validators.minLength(4)]),
UserNameValidator.cannotContainSpaces],
password: [null,Validators.compose([Validators.required])]
})
}
signup.component.html
<form [formGroup]="form" >
<div class="form-group">
<label for="username">Username: </label>
<input
class= "form-control"
type="text"
formControlName="username">
<div *ngIf="username.touched &&
form.controls['username'].getError('required')"
class="alert alert-danger">Username cannot be empty
</div>
<div *ngIf="form.controls['username'].getError('minlength')" class =
"alert alert-danger">
Username should have atlest
{{username.errors.minlength.requiredLength}} characters
</div>
<div
*ngIf="form.controls.username.hasError('containsSpaces')"
class="alert alert-danger" > Username Can't Contains Spaces</div>
</div>
static cannotContainSpaces(control:Control):Promiseand return a new Promise that wraps the value you want it to resolve to something likePromise.resolve(username.indexOf(' ')>=0 ? {'containsSpace':true} : null)- shaunhusain