ng2-validation 在用户与表单交互后触发验证

ng2-validation trigger validation after user interact with the form

我正在使用 ng2-validation 模块来验证我的表单,它在验证方面工作正常。问题是,当我加载页面时,即使我从未接触过表单,表单也会出现验证错误,所以我需要在用户使用表单之后进行验证,而不是在页面加载时进行。

这是我的表单模板:

<form class="form" id="contact-form" #contactForm="ngForm" (ngSubmit)="onSubmit()">

  <input type="hidden" name="your-subject" [(ngModel)]="model.subject" #subject="ngModel">

  <div class="form-group" [ngClass]="{'has-danger': name.errors?.required}">
    <input class="form-control" type="text" placeholder="Nombre" name="your-name"
           [ngClass]="{'form-control-danger': name.errors?.required}"
           [(ngModel)]="model.name"
           #name="ngModel" required>
  </div>
  <label *ngIf="name.errors?.required" id="name-error" class="error help-block" for="name">
    Introduzca su nombre
  </label>

  <div class="form-group" [ngClass]="{'has-danger': phone.errors?.number}">
    <input class="form-control" type="text" placeholder="Teléfono" name="your-phone"
           [ngClass]="{'form-control-danger': phone.errors?.number}"
           [(ngModel)]="model.phone"
           #phone="ngModel" number>
  </div>
  <label *ngIf="phone.errors?.number" id="phone-error" class="error help-block" for="phone">
    Introduzca número de télefono válido
  </label>

  <div class="form-group" [ngClass]="{'has-danger': email.errors?.required || email.errors?.email }">
    <input type="text" placeholder="Email" name="your-email" class="form-control"
           [ngClass]="{'form-control-danger': email.errors?.required || email.errors?.email}"
           [(ngModel)]="model.email"
           #email="ngModel" email required>
  </div>
  <label *ngIf="email.errors?.required" id="email-error" class="error help-block" for="email">
    Introduzca su correo electrónico
  </label>
  <label *ngIf="email.errors?.email && !email.errors?.required" id="email-error" class="error help-block" for="email">
    Introduzca un correo electrónico válido
  </label>

  <div class="form-group" [ngClass]="{'has-danger': message.errors?.required }">
    <textarea rows="4" placeholder="Mensaje" name="your-message" class="form-control"
              [ngClass]="{'form-control-danger': message.errors?.required }"
              [(ngModel)]="model.message"
              #message="ngModel" required></textarea>
  </div>
  <label *ngIf="message.errors?.required" id="message-error" class="error help-block" for="message">
    Déjenos su mensaje
  </label>

  <div class="form-group">
    <label class="btn-label" for="input-btn">
      <input class="btn-input" type="submit" value="enviar" id="input-btn" [disabled]="!contactForm.form.valid">
    </label>
  </div>

</form>

如果你想在触摸某个字段时显示验证错误,你只需使用 touched:

<label *ngIf="name.errors?.required && name.touched">
  Introduzca su nombre
</label>

这将在用户访问该字段并且该字段失去焦点后显示错误。如果您想在用户在字段中输入内容后显示消息,请使用 dirty.