在嘗試實現自定義同步驗證程序時,出現錯誤「預期驗證程序返回Promise或Observable」。我正在使用FormControl和FormGroup類來構建驗證器。Angular 2中的同步驗證最終版本
從測試版到最終版本的這種變化令人困惑。請幫助我。
由於提前
請在下面找到我的代碼是一樣的:
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>
自己沒有這樣做,所以沒有添加作爲答案,但可能會嘗試使你的函數'靜態cannotContainSpaces(control:Control):Promise'並返回一個新的Promise,它將你想要的值解析爲' Promise.resolve(username.indexOf('')> = 0?{'containsSpace':true}:null)' – shaunhusain