我試圖檢查電子郵件字段和確認電子郵件字段是否相互匹配。也就是說,用戶輸入他們的電子郵件,然後他們必須再次確認。我想要匹配/驗證發生模糊(當用戶按下輸入或文本字段失去焦點)。檢查電子郵件是否匹配模糊
這是我的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和反應形式。
你能去了在有關如何使用此更深入:this.Form.get( '電子郵件')的錯誤?非常感謝你的'迷你教程'。超級有用! – Euridice01
例如如果我想在我的ts文件中執行某些操作:if(Form.valid){this; this.displayErrors = false; } – Euridice01
我修改了我的示例以回答您的評論。如果你認爲它的確有用,你會介意將這個答案標記爲已接受的答案嗎? – AngularChef