在Angular2中将附加值传递给自定义验证器?

时间:2016-06-14 13:52:14

标签: validation angular

我有一个验证器,用于检查用户的电子邮件地址是否唯一,为此,我还需要传入用户ID,以便它不包含在唯一的检查中。实现这一目标的最佳方法是什么?

据我所知,验证者只能访问控制值。我正在连接我的验证器:

<input #emailAddress="ngForm" type="text" [(ngModel)]="user.emailAddress" ngControl="emailAddress" required userExists />

目前我能够实现它的唯一方法是在验证器上设置一个静态值,这是不理想的!这是验证器的完整代码:

import { NG_ASYNC_VALIDATORS, Control } from '@angular/common';
import { Directive, provide, forwardRef, Attribute } from '@angular/core';
import { UserService } from './user.service';
import { User } from './user.model';

interface ValidationResult {
    [key: string]: boolean;
}

@Directive({
    selector: '[userExists][ngModel]',
    providers: [
        provide(NG_ASYNC_VALIDATORS, {
            useExisting: forwardRef(() => UserExistsValidator),
            multi: true
        })
    ]
})
export class UserExistsValidator {
    public static user: User;

    constructor(private _userService: UserService) { }

    validate(control: Control): Promise<ValidationResult> {
        return new Promise((resolve, reject) => {
            this._userService.exists(control.value, UserExistsValidator.user.id).subscribe(
                (response: any) => {
                    if (response.exists)
                        return resolve({ userExists: { valid: false } });
                    else
                        return resolve(null);
                },
                (error: any) => { console.log(error); }
            )
        });
    }
}

1 个答案:

答案 0 :(得分:0)

我会使用共享服务

@Injectable()
class ValidatorParam {
  value:string; // could also be an observable
}
@Directive({
    selector: '[userExists][ngModel]',
    providers: [
        { provide: NG_ASYNC_VALIDATORS, 
            useExisting: forwardRef(() => UserExistsValidator),
            multi: true
        })
    ]
})
export class UserExistsValidator {
    public static user: User;

    constructor(private _userService: UserService, private _param:ValidatorParam) { }

    validate(control: Control): Promise<ValidationResult> {
        return new Promise((resolve, reject) => {
            this._param.... // don't know what you want to do with it
            this._userService.exists(control.value, UserExistsValidator.user.id).subscribe(
                (response: any) => {
                    if (response.exists)
                        return resolve({ userExists: { valid: false } });
                    else
                        return resolve(null);
                },
                (error: any) => { console.log(error); }
            )
        });
    }
}
@Component({
  selector: '...',
  providers: [ValidatorParam],
  template: `
<input #emailAddress="ngForm" type="text" [(ngModel)]="user.emailAddress" ngControl="emailAddress" required userExists />
`})
 export class MyComponent {
   constructor(private _validatorParam:ValidatorParam) {
     this._validatorParam.value = xxx;
   }
 }

这样,每个组件只能有一个服务。如果此组件中有多个输入元素,则需要共享该服务。

警告:我没试过。