代码之家  ›  专栏  ›  技术社区  ›  Deadpool

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

  •  0
  • Deadpool  · 技术社区  · 8 年前

    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必须给出错误。

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

    enter image description here

    3 回复  |  直到 8 年前
        1
  •  22
  •   SiddAjmera    8 年前

    你可以加一个 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 用一个更适合你的。

        2
  •  19
  •   Saad Mehmood    8 年前

    更换此线路

    <input type="email" name="email" ngModel #email="ngModel" required>
    

    具有

    <input type="email" name="email" ngModel #email="ngModel" required email>// add email attribute
    
        3
  •  0
  •   Geetanshu Gulati    8 年前

    推荐文章