3

我正在使用该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>
4

1 回答 1

2

如果要在触摸字段时显示验证错误,只需使用touched

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

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

于 2017-11-21T19:03:27.347 回答