gpt4 book ai didi

javascript - Angular - 模板驱动的表单 - 电子邮件验证未发生

转载 作者:行者123 更新时间:2023-12-01 07:09:17 25 4
gpt4 key购买 nike

我正在制作一个简单的模板驱动表单,其中包含“电子邮件验证”(不是通过响应式表单)。因此,required、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>

Note: Though required validation of email is taking place, but as the pattern or data entered is not correct, the 2nd validation in email validation div must give error.



结果: (电子邮件有效且其模式不会自动给出错误)

enter image description here

最佳答案

您可以添加 email归因于您的电子邮件输入。但是,这不会使它对 xxx@xxx 模式的某些东西无效。在您的情况下,我认为这不是有效的电子邮件。

我建议你使用 pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{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>

尝试这两种方法 Sample StackBlitz并使用更适合您的那个。

关于javascript - Angular - 模板驱动的表单 - 电子邮件验证未发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52830614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com