簡體   English   中英

angular2異步表單驗證

[英]angular2 async form validation

我正在嘗試使用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返回undefined。

    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]
  });         
};

EDIT1

您需要利用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>

有關詳細信息,請參閱此文章:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM