Angular 2:长度验证不起作用

时间:2017-04-26 16:50:14

标签: javascript angular angular2-forms angular-validation

我试图简单地从Angular网站复制演练,但无法进行长度验证:

<input 
  style="display:inline-block;min-width:150px" 
  class="form-input" 
  id="phone"
  required 
  minlength="4" 
  maxlength="24"
  type="number" 
  name="phone" 
  [(ngModel)]="client.phone" 
  #phone="ngModel" /> 

  <!-- required works, minlength and maxlength always false -->
  {{ phone.hasError('required') }} {{ phone.hasError('minlength') }} {{ phone.hasError('maxlength') }}

<div *ngIf="phone.errors && (phone.dirty || phone.touched)"
   class="alert alert-danger">
  <div [hidden]="!phone.errors.required">
    Name is required
  </div>
  <div [hidden]="!phone.errors.minlength">
    Name must be at least 4 characters long.
  </div>
  <div [hidden]="!phone.errors.maxlength">
    Name cannot be more than 24 characters long.
  </div>
</div>

我必须遗漏一些简单的内容,但由于某些原因,required验证会根据输入进行更改,但minlengthmaxlength始终都是false,无论多长时间我的意见是。

1 个答案:

答案 0 :(得分:4)

因为数字类型没有长度属性

enter image description here

https://github.com/angular/angular/issues/15053

存在错误

你可以解决它:

[ngModel]="client.phone" (ngModelChange)="client.phone = $event + ''"

<强> Plunker Example

<强>更新

由于在 4.2.0-beta.0 (2017-05-04)中引入了最小和最大验证器,因此您可以查看https://github.com/angular/angular/pull/15813/commits/52b0ec8062381e7285b5f66aa83008edfbf02af3