[英]Angular - Template driven form - Email validation not happening
I am making a simple template-driven form with 'Email Validation' in it (Not by Reactive Forms). 我正在制作一个简单的模板驱动表单,其中带有“电子邮件验证”(不是通过响应表单)。 So, required, minlength, maxlength are working fine. 因此,必需的minlength和maxlength都可以正常工作。 But, when I try email to be valid, its failing. 但是,当我尝试使电子邮件有效时,它会失败。 Can someone help me out? 有人可以帮我吗?
abc.component.html 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. 注意:虽然正在进行电子邮件的必要验证,但是由于输入的模式或数据不正确, 因此电子邮件验证div中的第二次验证必须给出错误。
Result: (Email valid and its pattern not automatically giving error) 结果:(电子邮件有效,其模式未自动给出错误)
Replace this line 替换此行
<input type="email" name="email" ngModel #email="ngModel" required>
with 与
<input type="email" name="email" ngModel #email="ngModel" required email>// add email attribute
You could add an email
attribute to your Email Input. 您可以在电子邮件输入中添加email
属性。 But then that would not in-validate it for something of the pattern xxx@xxx
which I think would not be a valid email in your case. 但这不会使xxx@xxx
模式的内容xxx@xxx
,我认为在您的情况下这不是有效的电子邮件。
I suggest you use pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\\.[az]{2,4}$"
instead. 建议您使用pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\\.[az]{2,4}$"
。 Then, where you're showing the error message, you should check for email.errors?.pattern
instead. 然后,在显示错误消息的地方,应改为检查email.errors?.pattern
。
Give this a try: 试试看:
<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>
Try both the approaches on this Sample StackBlitz and use the one that suits you better. 在此示例StackBlitz上尝试两种方法,并使用更适合您的方法。
在输入标记中使用“模式= regrex”,并使用验证电子邮件?错误?模式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.