[英]Angular - Template driven form - Email validation not happening
我正在制作一個簡單的模板驅動表單,其中帶有“電子郵件驗證”(不是通過響應表單)。 因此,必需的minlength和maxlength都可以正常工作。 但是,當我嘗試使電子郵件有效時,它會失敗。 有人可以幫我嗎?
abc.component.html
<form #customForm="ngForm" (ngSubmit)="alpha(customForm)">
<input type="text" name="firstName" ngModel #firstName ="ngModel" required minlength="3" maxlength="10"><br/>
<div *ngIf="firstName.touched">
<p *ngIf="firstName.errors?.required">First Name is Required!!!</p>
<p *ngIf="firstName.errors?.minlength">First Name minimum 3 characters are required!!!</p>
<p *ngIf="firstName.errors?.maxlength">First Name max length is 10!!!</p>
</div>
<input type="email" name="email" ngModel #email="ngModel" required><br/>
<div *ngIf="email.touched">
<p *ngIf="email.errors?.required">Email is a required field!</p>
<p *ngIf="email.errors?.email">This is not a valid Email!!!</p>
</div>
<button type="submit" [disabled]="customForm.invalid">Submit</button>
</form>
注意:雖然正在進行電子郵件的必要驗證,但是由於輸入的模式或數據不正確, 因此電子郵件驗證div中的第二次驗證必須給出錯誤。
結果:(電子郵件有效,其模式未自動給出錯誤)
替換此行
<input type="email" name="email" ngModel #email="ngModel" required>
與
<input type="email" name="email" ngModel #email="ngModel" required email>// add email attribute
您可以在電子郵件輸入中添加email
屬性。 但這不會使xxx@xxx
模式的內容xxx@xxx
,我認為在您的情況下這不是有效的電子郵件。
建議您使用pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\\.[az]{2,4}$"
。 然后,在顯示錯誤消息的地方,應改為檢查email.errors?.pattern
。
試試看:
<input
type="email"
name="email"
ngModel
#email="ngModel"
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"
required>
<br/>
<div *ngIf="email.touched">
<p *ngIf="email.errors?.required">Email is a required field!</p>
<p *ngIf="email.errors?.pattern">This is not a valid Email!!!</p>
</div>
在此示例StackBlitz上嘗試兩種方法,並使用更適合您的方法。
在輸入標記中使用“模式= regrex”,並使用驗證電子郵件?錯誤?模式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.