2017-01-30 101 views
6

我試圖檢查電子郵件字段和確認電子郵件字段是否相互匹配。也就是說,用戶輸入他們的電子郵件,然後他們必須再次確認。我想要匹配/驗證發生模糊(當用戶按下輸入或文本字段失去焦點)。檢查電子郵件是否匹配模糊

這是我的TS文件:

import {Component, OnInit} from '@angular/core'; 
import {User} from './user.interface'; 
import {FormBuilder, FormGroup, ValidatorFn} from '@angular/forms'; 

@Component({ 
    selector: 'my-email', 
    templateUrl: '/app/components/profile/email.component.html', 
    styleUrls:['styles.css'], 
}) 

export class EmailComponent implements OnInit { 

    public user : User; 
    Form : FormGroup; 

    ngOnInit() { 
     // initialize model here 
     this.user = { 
      Email: '', 
      confirmEmail: '' 
     } 
     if(this.Form.valid) { 
      this.displayErrors = false; 
     } 
    } 

    constructor(fb: FormBuilder, private cookieService: CookieService, private router: Router) { 
      this.Form = fb.group({ 
      email: [''], 
      confirmEmail: [''] 
     }, 
     { 
      validator: this.matchingEmailsValidator('email', 'confirmEmail') 
     }); 


    } 

    save(model: User, isValid: boolean) { 
     // call API to save customer 
     //save email 

    } 

    matchingEmailsValidator(emailKey: string, confirmEmailKey: string): ValidatorFn { 
     return (group: FormGroup): {[key: string]: any} => { 

      let email = group.controls[emailKey]; 
      let confirmEmail = group.controls[confirmEmailKey]; 

      if (email.value !== confirmEmail.value) { 
       return { 
        mismatch: true 
       }; 
      } 
     }; 
    } 
} 

這是我的觀點:

<form [formGroup]="Form" novalidate (ngSubmit)="Form.valid && save(Form.value, Form.valid)"> 
    <div class="container-fluid"> 
    <div id = "container" class="contain" style="text-align: center"> 
     <div> 
      <fieldset class="form-group"> 
      <label id = "rounded" class="item item-input .col-md-6 .col-md-offset-3"> 
       <input class="email-address-entry form-control" name="email" type="email" placeholder="[email protected]" formControlName="email" pattern="^(\\w|[0-9.!#$%&’*+/=?^_\`{|}~-])[email protected](\\w|[0-9-])+(?:‌​[.](\\w|[0-9-])+)*$"/> 
      </label> 
       <p class="Reenter-your-email">Reenter your email to confirm</p> 
      <label id = "rounded" class="item item-input"> 
       <input class="email-address-entry form-control" (blur)="displayErrors=true" name="confirmEmail" type="email" placeholder="[email protected]" formControlName="confirmEmail" validateEqual="email"/> 
      </label> 
      </fieldset> 
     </div> 
     <div> 
      <label class="entry-invalid"> 
      <p *ngIf="displayErrors && !Form.get('email').valid">The email you entered does not match.</p> 
      </label> 
     </div> 
     <div (click)="Form.get('email').length > 0 ? save(Form.value, Form.valid) : NaN" class="{{ Form.get('email').length > 0 ? 'container-fluid anchorBottomHighlight' : 'container-fluid anchorBottom'}}"> 
      <label class="footerLabel">Confirm</label> 
     </div> 
    </div> 
    </div> 
</form> 

目前,與它的設置方式,發生了驗證,但它只有在正確的比賽是沒有得到清除輸入。我想知道如何正確設置我的視圖?所以當設置正確的匹配時,驗證消息顯示/隱藏。

此外,它似乎是Form.get('email').length > 0永遠不會大於0 /從未命中,所以我的標籤不會切換爲可點擊。

我正在使用Angular 2和反應形式。

回答

4

看起來,你混合這兩種形式的語法:模板驅動形式模型驅動的形式

由於您在類中聲明瞭表格模型FormBuilder,因此我假設您需要模型驅動表格

這意味着您的字段不需要像[(ngModel)]#EmailAddress這樣的屬性。

取而代之的是:

<input type="email" [(ngModel)]="user.EmailAddress" required #EmailAddress="ngModel"> 

這樣寫:

你的校驗
<!-- Now I'm using `formControlName` to bind the field to the model --> 
<!-- Its value must match one of the names you used in the FormBuilder --> 
<input type="email" formControlName="email"> 

都必須在FormBuilder聲明。不只是matchingEmailsValidator,也required

this.Form = fb.group({ 
    email: ['', Validators.required], 
    confirmEmail: ['', Validators.required] 
}, 
{ 
    validator: this.matchingEmailsValidator('email', 'confirmEmail') 
}); 

現在你可以用下面的語法訪問一個字段:

// In the class 
this.Form.get('email').value 
this.Form.get('email').errors 
<!-- In the template --> 
{{ Form.get('email').value }} 
{{ Form.get('email').errors }} 

您可以使用這些語法的顯示錯誤。例如:

<input type="email" formControlName="email"> 
<p *ngIf="Form.get('email').dirty && Form.get('email').errors.required"> 
    This field is required. 
</p> 

在上面的例子中,如果email字段已經被觸摸我顯示錯誤消息(即,用戶試圖進入的東西)和required錯誤存在。

您還可以通過使用瀏覽器的開發工具檢查表單的標記來驗證您的驗證規則是否已實施。 Angular應該將.ng-invalid.ng-valid等類添加到具有驗證規則的<input>標記中。

最後,關於您的問題查看電子郵件匹配模糊。你不能推遲Angular的驗證,它會實時發生(如用戶輸入)。但你可以等待模糊事件顯示錯誤

結合我前面的例子中這最後的意見,這裏是你如何能應該的錯誤,如果電子郵件字段爲空,它已失去焦點(blur事件):

<input type="email" formControlName="email" (blur)="displayErrors=true"> 
<p *ngIf="displayErrors && Form.get('email').dirty && Form.get('email').errors.required"> 
    This field is required. 
</p> 

UPDATE(01尤麗狄茜後-FEB-2017)公佈this Plunkr

  • 你還有wayyyyy得多驗證代碼在您的模板。就像我說過的,所有驗證者都應該在FORM MODEL中聲明(與FormBuilder一起)。更具體地說:
    • email字段中的pattern="..."屬性應在表單模型中替換爲Validators.pattern()
    • 什麼是confirmEmail字段中的validateEqual="email"屬性?你沒有在任何地方使用。
  • 主要問題是您的測試顯示錯誤信息:*ngIf="displayErrors && !Form.get('email').valid && Form.get('email').error.mismatch"
    • 首先,財產是errors與「s」,而不是error
    • 另外,您的自定義驗證程序在窗體本身上設置錯誤,而不是在電子郵件字段中。這意味着您應該從Form.errors.mismatch而不是Form.get('email').errors.mismatch檢索您的mismatch自定義錯誤。

下面是更新,工作Plunkr:https://plnkr.co/edit/dTjcqlm6rZQxA7E0yZLa?p=preview

+0

你能去了在有關如何使用此更深入:this.Form.get( '電子郵件')的錯誤?非常感謝你的'迷你教程'。超級有用! – Euridice01

+0

例如如果我想在我的ts文件中執行某些操作:if(Form.valid){this; this.displayErrors = false; } – Euridice01

+0

我修改了我的示例以回答您的評論。如果你認爲它的確有用,你會介意將這個答案標記爲已接受的答案嗎? – AngularChef

相關問題