2017-01-17 71 views
1

我想驗證輸入字段應該只允許大於零的正數,爲此我使用Validators.compose()以及一些規則。問題是我無法驗證這個字段,但它不能按預期工作。難道我做錯了什麼?我怎麼修復它?由於Ionic 2 RegEX驗證不起作用

打字稿代碼:

export class SignupPage { 
    public signup: FormGroup; 

    constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder) { 
     // setting up sign up form 
     this.signup = formBuilder.group({ 
      "name": ["", Validators.required], 
      "age": ["", Validators.compose([Validators.required, Validators.pattern('^[1-9]\d*$')])], 
      "city": ["", Validators.required] 
     }) 
    } 

    onSubnmit(form) { 
     console.log(form); 

     let user = { 
      'name': form.name, 
      'age': form.age, 
      'city': form.city 
     } 
    } 

HTML代碼:

<form [formGroup]="signup" (ngSubmit)="onSubmit(this.signup.value)"> 
    <ion-list class="signup-input"> 
     <ion-item> 
      <ion-label floating>What is your name?</ion-label> 
      <ion-input type="text" formControlName="name" [class.invalid]="!signup.valid && (signup.controls.name.dirty || submitAttempt)"></ion-input> 
     </ion-item> 
     <ion-item *ngIf="!signup.controls.name.valid && (signup.controls.name.dirty || submitAttempt)" > 
      <small>Please fill out this field.</small> 
     </ion-item> 

     <ion-item> 
      <ion-label floating>How old are you?</ion-label> 
      <ion-input type="text" formControlNale="age" [class.invalid]="!signup.controls.age.valid && (signup.controls.age.dirty || submitAttempt)"></ion-input> 
     </ion-item> 
     <ion-item *ngIf="!signup.controls.age.valid && (signup.controls.age.dirty || submitAttempt)" > 
      <small>Please enter a valid age.</small> 
     </ion-item> 

     <ion-item> 
      <ion-label floating>What is your city?</ion-label> 
      <ion-input type="text" formControlName="city" [class.invalid]="!signup.controls.city.valid && (signup.controls.city.dirty || submitAttempt)"></ion-input> 
     </ion-item> 
     <ion-item *ngIf="!signup.controls.city.valid && (signup.controls.city.dirty || submitAttempt)" > 
      <small>Please fill out this field.</small> 
     </ion-item> 

    </ion-list> 
    <ion-grid> 
     <ion-row> 
      <div class="signup-btn"> 
       <button ion-button block width-90 type="submit" [disabled]="!this.signup.valid">Get in</button> 
      </div> 
     </ion-row> 
    </ion-grid> 
</form> 

,這是它的樣子:

Result

回答

3

錯字在指令名

formControlNale="age" 

應該

formControlName="age" 
+0

愚蠢的錯誤,感謝您的幫助! :) –