如何在离子3中添加模板驱动形式的验证



如何在ionic 3中验证手机号码,这里我使用了ng模型,有什么例子可以做吗?

<ion-list>
<ion-item margin-bottom>
<ion-input type="number" id="phone"   name="phone"  [(ngModel)]="data.phone" #username="ngModel" placeholder="Mobile"></ion-input>

</ion-item>

<ion-item margin-bottom> 
<ion-input type="password" id="password" name="password"  [(ngModel)]="data.password" placeholder="*Password"></ion-input>
</ion-item>
<div style="text-align:center;">
<button ion-button color="primary" type="submit" (click)="login()">
<ion-icon ios="ios-log-in" md="md-log-in"></ion-icon>
Login</button>
</div>
</ion-list>

.html文件代码

<ion-list>
<ion-item margin-bottom>
<ion-input type="number" id="phone"   name="phone"  [(ngModel)]="data.phone" #username="ngModel" placeholder="Mobile" (ionChange)='validateForm()'></ion-input> 
<br/>
{{phoneErrorMessage}}
</ion-item>
<ion-item margin-bottom> 
<ion-input type="email" id="email" name="email"  [(ngModel)]="data.email" placeholder="*Password" (ionChange)='validateForm()'></ion-input>
<br/>
{{emailErrorMessage}}
</ion-item>
<div style="text-align:center;">
<button ion-button color="primary" type="submit" (click)="login()">
<ion-icon ios="ios-log-in" md="md-log-in"></ion-icon>Login
</button>
</div>
</ion-list>

.ts文件代码

public phoneErrorMessage = '';
public emailErrorMessage = '';
public data = {email:'',phone:''}
validateForm(){
var phoneValidationFlag = false ;
var emailValidationFlag = false ;

if (this.data.phone == "") {
this.phoneErrorMessage = "Name must be filled out";
phoneValidationFlag = false ; 
}else{
this.phoneErrorMessage = '';
phoneValidationFlag = true;
}

var emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$/;
if (!emailRegex.test(this.data.email)){  
this.emailErrorMessage =  'Please enter valid email';
emailValidationFlag = false
}else{
this.emailErrorMessage = '';
emailValidationFlag = true;
}

return (emailValidationFlag && phoneValidationFlag) ? true : false ;
}


login(){
if(this.validateForm()){
//everything validated and you can excute your api call in this if section
}
}

相关内容

  • 没有找到相关文章