正则表达式在Angular2中不起作用

时间:2017-05-09 15:47:26

标签: javascript angular

我在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> 

2 个答案:

答案 0 :(得分: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)">

答案 1 :(得分:2)

您可以改为使用内置模式验证器。像这样:

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

注意:电子邮件现在是一个不好的例子,因为Angular支持type =&#34; email&#34;验证。但它展示了使用模式验证器的机制。