2017-04-18 64 views
4

我有一個簡單的輸入是爲了一個電話號碼,我想驗證,只有數字和長度是10位數字。Angular 2:簡單的輸入驗證

<input [(ngModel)]="client.phone" class="form-input" name="phone" type="phone" [value]="client.phone"> 

我能做些什麼來驗證這一點沒有使用FormBuilder?似乎FormBuilder只是使事情複雜化,我只想驗證這一個輸入。

+0

你是否還在尋找留在模板驅動的形式? – Winnemucca

+0

這似乎更簡單,我是Angular2的新手 –

+0

我正在尋找接近此角度的方法 –

回答

2

<input type="number" name="phone" max="10">

可以使用型號和最大

+0

這不會將數字限制在1到10之間嗎?我認爲OP需要1到10位數字。 – DeborahK

+0

^這是正確的 –

1

這裏是我的Pluralsight課程的例子。這第一個例子是使用模板驅動的表單。它使用一個簡單的模式來驗證電子郵件地址:

  <div class="form-group" 
       [ngClass]="{'has-error': (emailVar.touched || emailVar.dirty) && !emailVar.valid }"> 
       <label class="col-md-2 control-label" 
        for="emailId">Email</label> 

       <div class="col-md-8"> 
        <input class="form-control" 
          id="emailId" 
          type="email" 
          placeholder="Email (required)" 
          required 
          pattern="[a-zA-Z0-9._%+-][email protected][a-zA-Z0-9.-]+" 
          [(ngModel)]="customer.email" 
          name="email" 
          #emailVar="ngModel" /> 
        <span class="help-block" *ngIf="(emailVar.touched || emailVar.dirty) && emailVar.errors"> 
         <span *ngIf="emailVar.errors.required"> 
          Please enter your email address. 
         </span> 
         <span *ngIf="emailVar.errors.pattern"> 
          Please enter a valid email address. 
         </span> 

         <!-- This one does not work --> 
         <span *ngIf="emailVar.errors.email"> 
          Please enter a valid email address. 
         </span> 
        </span> 
       </div> 
      </div> 

本示例對同一事物使用Reactive Forms。

this.customerForm = this.fb.group({ 
     firstName: ['', [Validators.required, Validators.minLength(3)]], 
     lastName: ['', [Validators.required, Validators.maxLength(50)]], 
     email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-][email protected][a-z0-9.-]+')]], 
     sendCatalog: true 
    }); 

所以使用一個模式是非常多的角度技術。我只是把你指向HTML網站,因爲它提供了一些關於電話號碼模式的建議,你可以從中選擇和使用這些模式來代替我的示例中顯示的電子郵件模式。

讓我知道如果你想鏈接到關聯的github代碼。

3

通過內置的模式驗證這是很容易:

<input [(ngModel)]="client.phone" pattern="[0-9]{10}" class="form-input" name="phone" type="phone" [value]="client.phone">