angular2 异步表单验证

标签 angular angular2-forms

我正在尝试使用 Angular2 完成表单验证。

我正尝试通过异步调用查明用户名是否已被占用并在我的数据库中使用。

到目前为止,这是我的代码:

表单组件:

import {Component, OnInit} from 'angular2/core';
import {FORM_PROVIDERS, Control, ControlGroup, FormBuilder, Validators} from 'angular2/common';
import {Http, Headers, RequestOptions} from 'angular2/http';
import {ROUTER_DIRECTIVES, Router, RouteParams} from 'angular2/router';
import {ControlMessages} from './control.messages';
import {ValidationService} from './validation.service';

@Component({
    selector: 'account-form',
    templateUrl: './app/account/account.form.component.html',
    providers: [ROUTER_DIRECTIVES, CaseDataService],
    directives: [ControlMessages]
})

accountForm: ControlGroup;

constructor(private _accountService: AccountDataService,
    private _formBuilder: FormBuilder, private _router: Router, private _params?: RouteParams) {
    this.model = this._accountService.getUser();

    this.accountForm = this._formBuilder.group({
        'firstName': ['', Validators.required],
        'lastName': ['', Validators.required],
        'userName': ['', Validators.compose([ValidationService.userNameValidator, ValidationService.userNameIsTaken])],

....
}

验证服务:

export class ValidationService {


static getValidatorErrorMessage(code: string) {
    let config = {
        'required': 'Required',
        'invalidEmailAddress': 'Invalid email address',
        'invalidPassword': 'Invalid password. Password must be at least 6 characters long, and contain a number.',
        'mismatchedPasswords': 'Passwords do not match.',
        'startsWithNumber': 'Username cannot start with a number.'
    };
    return config[code];
}

static userNameValidator(control, service, Headers) {
    // Username cannot start with a number
    if (!control.value.match(/^(?:[0-9])/)) {
        return null;
    } else {
        return { 'startsWithNumber': true };
    }
}
  // NEEDS TO BE AN ASYNC CALL TO DATABASE to check if userName exists. 
// COULD userNameIsTaken be combined with userNameValidator??

static userNameIsTaken(control: Control) {
    return new Promise(resolve => {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json')

        // needs to call api route - _http will be my data service. How to include that?

        this._http.get('ROUTE GOES HERE', { headers: headers })
            .map(res => res.json())
            .subscribe(data => {
                console.log(data);
                if (data.userName == true) {
                    resolve({ taken: true })
                }
                else { resolve({ taken: false }); }
            })
    });
}
}

新代码(更新 x2)。 ControlGroup 返回未定义。

    this.form = this.accountForm;
    this.accountForm = this._formBuilder.group({
        'firstName': ['', Validators.required],
        'lastName': ['', Validators.required],
        'userName': ['', Validators.compose([Validators.required, this.accountValidationService.userNameValidator]), this.userNameIsTaken(this.form, 'userName')],
        'email': ['', Validators.compose([Validators.required, this.accountValidationService.emailValidator])],
        'password': ['', Validators.compose([Validators.required, this.accountValidationService.passwordValidator])],
        'confirm': ['', Validators.required]
    });         
};

userNameIsTaken(group: any, userName: string) {
    return new Promise(resolve => {

        this._accountService.read('/username/' + group.controls[userName].value)
            .subscribe(data => {
                data = data
                if (data) {
                    resolve({ taken: true })
                } else {
                    resolve(null);
                }
            });
    })
};

HTML:

<div class="input-group">
    <span class="input-group-label">Username</span>
    <input class="input-group-field" type="text" required [(ngModel)]="model.userName" ngControl="userName" #userName="ngForm">
    <control-messages control="userName"></control-messages>
    <div *ngIf="taken">Username is already in use.</div>
</div>

最佳答案

你应该这样定义你的异步验证器:

'userName': ['', ValidationService.userNameValidator, 
       ValidationService.userNameIsTaken],

而不是 Validators.compose 方法。事实上,这里是参数对应的:

'<field-name>': [ '', syncValidators, asyncValidators ]

此外,当用户名未被使用而不是`{taken: false}

时,您应该使用 null 进行解析
if (data.userName == true) {
  resolve({ taken: true })
} else {
  resolve(null);
}

有关详细信息,请参阅本文(“字段的异步验证”部分):

编辑

也许我的回答不够清楚。您仍然需要使用 Validators.compose,但前提是您有多个同步验证器:

this.accountForm = this._formBuilder.group({
    'firstName': ['', Validators.required],
    'lastName': ['', Validators.required],
    'userName': ['', Validators.compose([
             Validators.required,
             this.accountValidationService.userNameValidator
          ], this.userNameIsTaken],
    'email': ['', Validators.compose([
             Validators.required,
             this.accountValidationService.emailValidator
          ]],
    'password': ['', Validators.compose([
             Validators.required,
             this.accountValidationService.passwordValidator
          ]],
    'confirm': ['', Validators.required]
  });         
};

编辑1

您需要利用 ngFormControl 而不是 ngControl,因为您使用 FormBuilder 类定义控件。

<div class="input-group">
  <span class="input-group-label">Username</span>
  <input class="input-group-field" type="text" required [(ngModel)]="model.userName" [ngControl]="accountForm.controls.userName" >
  <control-messages [control]="accountForm.controls.userName"></control-messages>
  <div *ngIf="accountForm.controls.userName.errors && accountForm.controls.userName.errors.taken">Username is already in use.</div>
</div>

有关详细信息,请参阅本文:

关于angular2 异步表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36452392/

相关文章:

angular - 意外值 ‘HttpClient’

javascript - 来自 @Input 时,将 ngModel 分配给属性是未定义的

unit-testing - Angular2 组件 : Testing form input value change

angular - angular2中的表格

angular - angular2 中的多供应商是什么

单击后 Angular 禁用按钮?

angular - Observable:如果在 map() 之前,为什么不导致 subscribe() 成功函数?

跨应用程序实例的 Angular2 数据绑定(bind) - 如何停止?

css - 如何从底部强制 Angular Material 2 sidenav 内容

Angular2 v.2.3 - 让指令访问通过 formControlName 语法创建的 FormControl