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

角度模板驱动表单提交验证

  •  0
  • User123  · 技术社区  · 7 年前

    在angular js中,我们有$submited来填充提交点击时的错误消息。

    如何在提交时显示所有验证错误

    HTML格式:

    <form #nameForm="ngForm" novalidate (ngSubmit)="saveNameForm(formModel)">
    <div class="form-group">
       <label for="inputName" class="form-control-label"> Name</label>
       <input type="text" id="inputName" name="lotCode [(ngModel)]="formModel.name" #lotCode="ngModel" aria-describedby="nameHelp"
         autocomplete="new-password" required>
       <small id="nameHelp" class="text-danger" *ngIf="lotCode.invalid && lotCode.touched">Required</small>
    </div>
    
    <div class="form-group">
        <label for="inputDescription" class="form-control-label"> Description</label>
        <input type="text" id="inputDescription" name="desCode" [(ngModel)]="formModel.description" #desCode="ngModel" aria-describedby="descriptionHelp"
         autocomplete="new-password" required>
        <small id="descriptionHelp" class="text-danger" *ngIf="desCode.invalid && desCode.touched">Required</small>
    </div>
    
    <button type="submit">Submit </button>
    </form>
    

    组成部分:

     export class AppComponent  {
     formModel: FormModel= new FormModel();
     saveNameForm(formModel){
     console.log(formModel)
     }
     }
     export class FormModel {
     name: string;
     description:string;
     }
    

    https://stackblitz.com/edit/angular-rizsuy?file=src%2Fapp%2Fapp.component.ts

    2 回复  |  直到 7 年前
        1
  •  0
  •   Ghazni    7 年前
        2
  •  0
  •   nmg49    7 年前

    Angular使用相同的 form validation 原生HTML5就是这样。从一个角度来看。在下面的示例中,我们可以使用 *ngIf 控制消息的显示,以及 .dirty .touched 以确定用户是否与输入交互。

    docs

    <input id="name" name="name" class="form-control"
      required minlength="4" appForbiddenName="bob"
      [(ngModel)]="hero.name" #name="ngModel" >
    
      <div *ngIf="name.invalid && (name.dirty || name.touched)"
      class="alert alert-danger">
    
      <div *ngIf="name.errors.required">
        Name is required.
      </div>
      <div *ngIf="name.errors.minlength">
        Name must be at least 4 characters long.
      </div>
      <div *ngIf="name.errors.forbiddenName">
        Name cannot be Bob.
      </div>
    </div>
    
    推荐文章