简体   繁体   中英

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. But, when I try email to be valid, its failing. Can someone help me out?

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.

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. 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.

I suggest you use pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\\.[az]{2,4}$" instead. Then, where you're showing the error message, you should check for email.errors?.pattern instead.

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.

在输入标记中使用“模式= regrex”,并使用验证电子邮件?错误?模式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM