[英]Angular 4 reactive form Email validation by regular expression fail
我正在使用反應式表單來獲取用戶輸入。 對我使用的模式不滿意EmailValidator
。
emailRegEx = '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$';
this.email = new FormControl('', [Validators.required, Validators.pattern(emailRegEx)]);
和 HTML:
<input type="email" formControlName="email" [ngClass]="contactForm.get('email').errors && (contactForm.get('email').dirty || isButtonClicked) ? 'contact-input input-error' : 'contact-input'">
但事情就是這樣,由於某種原因,正則表達式在@
之后接受 4 個字符,沒有句點。 name@d
--> 錯誤
name@doma
--> 沒有錯誤name@domain.
--> 錯誤
name@domain.com
--> 沒有錯誤
我在多個在線正則表達式測試器中檢查了這個正則表達式,他們都只接受上面的最后一個例子,沒有一個接受第二個。
編輯:
正則表達式很好並且運行良好,問題是模式驗證器以某種方式沒有正確解析正則表達式,或者其他什么。
該模式作為字符串不正確。 實際上你在一個字符串中,所以要轉義 '.' 你需要使用雙反斜杠,如:
emailRegEx = '^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'
或者,如果您想避免這樣做,我建議使用:
emailRegEx = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/
編輯:請記住,這是一個簡單的模式,它排除了許多有效的電子郵件地址(請參閱 RFC 5322(第3.2.3和3.4.1節)和 RFC 5321 )。 例如,電子郵件驗證器中的角度構建使用以下模式
/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/
您可以使用提供太多驗證類型的 CustomValidator 包: https : //www.npmjs.com/package/ng2-validation
像這樣導入:
import { CustomValidators } from 'ng2-validation';
並在您的表單控件中使用它:
this.email = new FormControl('', [Validators.required, CustomValidators.email]);
問候,
我用這個:
/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/
import {Component} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
@Component({
templateUrl: './forgot-password.component.html',
styleUrls: ['./forgot-password.component.scss']
})
export class ForgotPasswordComponent {
psResetForm: FormGroup;
constructor(private fb: FormBuilder) {
this.psResetForm = fb.group({
'email': [null, Validators.compose([Validators.required, Validators.email])]
});
}
makeRequestToResetLink(formData, valid: boolean) {
if (valid) {
alert(formData.email);
}
}
}
您的模板應如下所示
<form [formGroup]="psResetForm" (ngSubmit)="makeRequestToResetLink(psResetForm.value,psResetForm.valid)">
<input type="email" formControlName="email"/>
<button type="submit">
submit
</button>
</form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.