yle*_*jen 4 validation angular2-forms angular2-formbuilder angular
我正在尝试实现异步验证器但没有成功......
我的组件创建了一个表单:
this.personForm = this._frmBldr.group({
lastname: [ '', Validators.compose([Validators.required, Validators.minLength(2) ]) ],
firstname: [ '', Validators.compose([Validators.required, Validators.minLength(2) ]) ],
birthdate: [ '', Validators.compose([ Validators.required, DateValidators.checkIsNotInTheFuture ]) ],
driverLicenceDate: [ '', Validators.compose([ Validators.required, DateValidators.checkIsNotInTheFuture ]), this.asyncValidationLicenceDate.bind(this) ],
}, {
asyncValidator: this.validateBusiness.bind(this),
validator: this.validateDriverLicenseOlderThanBirthdate,
});
Run Code Online (Sandbox Code Playgroud)
我的验证方法
validateBusiness(group: FormGroup) {
console.log('validateBusiness')
return this._frmService
.validateForm(group.value)
.map((validationResponse: IValidationResponse) => {
if (validationResponse) {
validationResponse.validations.forEach( (validationError: IValidationErrorDescription) => {
let errorMsg = validationError.display;
let errorCode = validationError.code;
validationError.fields.forEach( (fieldName: string) => {
console.log(fieldName);
let control = this.personForm.controls[fieldName];
let existingErrors = control.errors || {};
existingErrors[errorCode] = errorMsg;
control.setErrors(existingErrors);
});
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
所有验证都被称为successfuly,除了从未被调用的validateBusiness方法(在extra.asyncValidator
param中formbuilder.group
)...有人可以告诉我我做错了什么吗?
TX
TL; DR:通过分析您的用例,您可能需要解决方案2
问题
问题在于如何定义和使用异步验证器.
异步验证器定义为:
export interface AsyncValidatorFn {
(c: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
Run Code Online (Sandbox Code Playgroud)
这是因为FormBuilder.group()
实际上是在调用FormGroup
构造函数:
constructor(controls: {
[key: string]: AbstractControl;
}, validator?: ValidatorFn | null, asyncValidator?: AsyncValidatorFn | null);
Run Code Online (Sandbox Code Playgroud)
因此,异步验证器函数将接收一个AbstractControl
实例,在本例中,该FormGroup
实例是实例,因为验证器位于该FormGroup
级别.验证器需要返回a Promise
或Observable
of ValidationErrors
,如果不存在验证错误,则返回null.
ValidationErrors
被定义为字符串键和值的映射(任何你喜欢的).键实际上是定义验证错误类型的字符串(例如:"required").
export declare type ValidationErrors = {
[key: string]: any;
};
Run Code Online (Sandbox Code Playgroud)
AbstractControl.setErrors()?
- 在您的示例中,您定义的函数不返回任何内容,但实际上直接更改了控制错误.调用setErrors
仅适用于手动调用验证的情况,因此仅手动设置错误.相反,在您的示例中,方法是混合的,FormControl
s附加了将自动运行的FormGroup
验证函数,并且异步验证函数也会自动运行,尝试手动设置错误,从而设置有效性.这不行.
您需要采用以下两种方法之一:
AbstractControl
实例.如果您想保持一切清洁,那么您可以实现单独的验证功能.FormControl
验证只会处理一个控件.FormGroup
验证会将表单组的多个方面视为一个整体.
如果您想使用验证服务,它实际验证整个表单,就像您一样,然后将每个错误委派给每个适当的控件验证器,那么您可以使用解决方案2.这有点困难.
但是如果您可以在FormGroup
使用验证服务的级别上使用验证器,那么可以使用解决方案1来实现.
解决方案1 - 在FormGroup级别创建错误
让我们假设我们要输入名字和姓氏,但第一个名称需要与姓氏不同.并假设此计算需要1秒.
模板
<form [formGroup]="personForm">
<div>
<input type="text" name="firstName" formControlName="firstName" placeholder="First Name" />
</div>
<div>
<input type="text" name="lastName" formControlName="lastName" placeholder="Last Name" />
</div>
<p style="color: red" *ngIf="personForm.errors?.sameValue">First name and last name should not be the same.</p>
<button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
零件
以下validateBusiness
验证函数将返回Promise
:
import { Component, OnInit } from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup, ValidationErrors, Validators} from "@angular/forms";
import {Observable} from "rxjs/Observable";
import "rxjs/add/operator/delay";
import "rxjs/add/operator/map";
import "rxjs/add/observable/from";
@Component({
selector: 'app-async-validation',
templateUrl: './async-validation.component.html',
styleUrls: ['./async-validation.component.css']
})
export class AsyncValidationComponent implements OnInit {
personForm: FormGroup;
constructor(private _formBuilder: FormBuilder) { }
ngOnInit() {
this.personForm = this._formBuilder.group({
firstName: [ '', Validators.required ],
lastName: [ '', Validators.required ],
}, {
asyncValidator: this.validateBusiness.bind(this)
});
}
validateBusiness(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value.firstName !== control.value.lastName) {
resolve(null);
}
else {
resolve({sameValue: 'ERROR...'});
}
},
1000);
});
}
}
Run Code Online (Sandbox Code Playgroud)
或者,验证函数可以返回Observable
:
validateBusiness(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
return Observable
.from([control.value.firstName !== control.value.lastName])
.map(valid => valid ? null : {sameValue: 'ERROR...'})
.delay(1000);
}
Run Code Online (Sandbox Code Playgroud)
解决方案2 - 为多个控件协调验证错误
另一种选择是在表单更改时手动验证,然后将结果传递给一个observable,以后可以由FormGroup
和FormControl
异步验证器使用.
IValidationResponse
用于验证表单数据的验证服务的响应.
import {IValidationErrorDescription} from "./IValidationErrorDescription";
export interface IValidationResponse {
validations: IValidationErrorDescription[];
}
Run Code Online (Sandbox Code Playgroud)
IValidationErrorDescription
验证响应错误说明.
export interface IValidationErrorDescription {
display: string;
code: string;
fields: string[];
}
Run Code Online (Sandbox Code Playgroud)
BusinessValidationService
验证服务,用于实现验证表单数据的业务.
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/map';
import {IValidationResponse} from "../model/IValidationResponse";
@Injectable()
export class BusinessValidationService {
public validateForm(value: any): Observable<IValidationResponse> {
return Observable
.from([value.firstName !== value.lastName])
.map(valid => valid ?
{validations: []}
:
{
validations: [
{
code: 'sameValue',
display: 'First name and last name are the same',
fields: ['firstName', 'lastName']
}
]
}
)
.delay(500);
}
}
Run Code Online (Sandbox Code Playgroud)
FormValidationService
验证服务,用于为表单数据的更改构建异步验证器FormGroup
,FormControl
并订阅表单数据中的更改,以便将验证委托给验证回调(例如:) BusinessValidationService
.
它提供以下内容:
validateFormOnChange()
- 当表单更改时,它调用验证回调,validateFormCallback
并在触发验证FormGroup
和FormControl
使用时control.validateFormGroup()
.createGroupAsyncValidator()
- 为.创建异步验证器 FormGroup
createControlAsyncValidator()
- 为.创建异步验证器 FormControl
代码:
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/first';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/debounceTime';
import {AbstractControl, AsyncValidatorFn, FormGroup} from '@angular/forms';
import {ReplaySubject} from 'rxjs/ReplaySubject';
import {IValidationResponse} from "../model/IValidationResponse";
@Injectable()
export class FormValidationService {
private _subject$ = new ReplaySubject<IValidationResponse>(1);
private _validationResponse$ = this._subject$.debounceTime(100).share();
private _oldValue = null;
constructor() {
this._subject$.subscribe();
}
public get onValidate(): Observable<IValidationResponse> {
return this._subject$.map(response => response);
}
public validateFormOnChange(group: FormGroup, validateFormCallback: (value: any) => Observable<IValidationResponse>) {
group.valueChanges.subscribe(value => {
const isChanged = this.isChanged(value, this._oldValue);
this._oldValue = value;
if (!isChanged) {
return;
}
this._subject$.next({validations: []});
this.validateFormGroup(group);
validateFormCallback(value).subscribe(validationRes => {
this._subject$.next(validationRes);
this.validateFormGroup(group);
});
});
}
private isChanged(newValue, oldValue): boolean {
if (!newValue) {
return true;
}
return !!Object.keys(newValue).find(key => !oldValue || newValue[key] !== oldValue[key]);
}
private validateFormGroup(group: FormGroup) {
group.updateValueAndValidity({ emitEvent: true, onlySelf: false });
Object.keys(group.controls).forEach(controlName => {
group.controls[controlName].updateValueAndValidity({ emitEvent: true, onlySelf: false });
});
}
public createControlAsyncValidator(fieldName: string): AsyncValidatorFn {
return (control: AbstractControl) => {
return this._validationResponse$
.switchMap(validationRes => {
const errors = validationRes.validations
.filter(validation => validation.fields.indexOf(fieldName) >= 0)
.reduce((errorMap, validation) => {
errorMap[validation.code] = validation.display;
return errorMap;
}, {});
return Observable.from([errors]);
})
.first();
};
}
public createGroupAsyncValidator(): AsyncValidatorFn {
return (control: AbstractControl) => {
return this._validationResponse$
.switchMap(validationRes => {
const errors = validationRes.validations
.reduce((errorMap, validation) => {
errorMap[validation.code] = validation.display;
return errorMap;
}, {});
return Observable.from([errors]);
})
.first();
};
}
}
Run Code Online (Sandbox Code Playgroud)
AsyncFormValidateComponent模板
定义firstName
和lastName
FormControl
它们内部的小号personForm
FormGroup
.对于这个例子,条件是,firstName
并且lastName
应该是不同的.
<form [formGroup]="personForm">
<div>
<label for="firstName">First name:</label>
<input type="text"
id="firstName"
name="firstName"
formControlName="firstName"
placeholder="First Name" />
<span *ngIf="personForm.controls['firstName'].errors?.sameValue">Same as last name</span>
</div>
<div>
<label for="lastName">Last name:</label>
<input type="text"
id="lastName"
name="lastName"
formControlName="lastName"
placeholder="Last Name" />
<span *ngIf="personForm.controls['lastName'].errors?.sameValue">Same as first name</span>
</div>
<p style="color: red" *ngIf="personForm.errors?.sameValue">First name and last name should not be the same.</p>
<button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
AsyncValidateFormComponent
该组件用作使用该实现验证的示例FrmValidationService
.由于此组件有自己的此服务实例providers: [FormValidationService]
.由于Angular分层注入器功能,一个注入器将与此组件关联,并且将为每个实例创建一个此服务实例AsyncValidateFormComponent
.因此能够在每个组件实例的基础上跟踪此服务内的验证状态.
import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/from';
import {FormValidationService} from "../services/form-validation.service";
import {BusinessValidationService} from "../services/business-validation.service";
@Component({
selector: 'app-async-validate-form',
templateUrl: './async-validate-form.component.html',
styleUrls: ['./async-validate-form.component.css'],
providers: [FormValidationService]
})
export class AsyncValidateFormComponent implements OnInit {
personForm: FormGroup;
constructor(private _formBuilder: FormBuilder,
private _formValidationService: FormValidationService,
private _businessValidationService: BusinessValidationService) {
}
ngOnInit() {
this.personForm = this._formBuilder.group({
firstName: ['', Validators.required, this._formValidationService.createControlAsyncValidator('firstName')],
lastName: ['', Validators.required, this._formValidationService.createControlAsyncValidator('lastName')],
}, {
asyncValidator: this._formValidationService.createGroupAsyncValidator()
});
this._formValidationService.validateFormOnChange(this.personForm, value => this._businessValidationService.validateForm(value));
}
}
Run Code Online (Sandbox Code Playgroud)
的AppModule
它使用的ReactiveFormsModule
是为了使用FormBuilder
,FormGroup
和FormControl
.还提供了BusinessValidationService
.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { AsyncValidateFormComponent } from './async-validate-form/async-validate-form.component';
import {BusinessValidationService} from "./services/business-validation.service";
@NgModule({
declarations: [
AppComponent,
AsyncValidateFormComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule
],
providers: [
BusinessValidationService
],
bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5100 次 |
最近记录: |