2017-05-09 66 views
2

我在Angular2代碼中正則表達式,我試圖驗證表單是否包含字符串或整數,但它無法正常工作。如果我把數字寫入表格,它應該說「成功」,但它不會。正則表達式在Angular2中不起作用

app.component.ts

formText: string = ""; 

formValidate(cardNumber1: string):void{ 
var re = /^[0-9]+$/; 

if(!re.test(("cardNumber1"))){ 
    this.formText = "Please enter numbers only"; //even if i enter numbers, it still says "Please enter numbers only". 
}else{ 
    this.formText = "Success"; 
} 

} 

app.component.html

<input type="text" #cardNumber1 name="card-number1" class="card-form" 
    id="card-number1" cardNumber1.value=""> 

    <div class="form-text">{{formText}}</div> 
+0

您的HTML中存在語法錯誤。 –

+0

沒有足夠的信息。你如何從TS文件的輸入中獲取字符串? –

+0

我在app.component.html中有一個按鈕 Pleinair

回答

2

試試這個

app.component.ts

formText: string = ""; 

formValidate(cardNumberValue: string):void{ 


    var re = /^[0-9]+$/; 

    if(!re.test(cardNumberValue)){ 
     this.formText = "Please enter numbers only"; 
    }else{ 
     this.formText = "Success"; 
    } 

} 

app.component.html

<input type="button" value="pay" class="pay-btn" id="credit-card-pay" (click)="formValidate(cardNumber1.value)"> 
+0

它工作:)謝謝 – Pleinair

2

你也可以使用內置的模式驗證。事情是這樣的:

   <div class="col-md-8"> 
        <input class="form-control" 
          id="emailId" 
          type="email" 
          placeholder="Email (required)" 
          required 
          pattern="[a-z0-9._%+-][email protected][a-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> 
        </span> 
       </div> 

注:電子郵件現在是一個壞榜樣,因爲角度支持TYPE =「電子郵件」驗證。但它演示了使用模式驗證程序的機制。