我想在ionic 3中验证电子邮件和电话号码,但是出了点问题。我不能在表单验证中使用ngModel。
这是一个错误:
ngModel不能用于通过父formGroup指令注册表单控件。尝试改用formGroup的合作伙伴指令“ formControlName”。
这是我的html表单
<form (ngSubmit)="done()" #registerForm="ngForm" [formGroup]="registerForm">
<ion-col style="padding: 0px;" >
<ion-item>
<ion-input type="number" formControlName="mobileNumber" placeholder="971000000000" name="Mobile" [(ngModel)]="register.Mobile" [brmasker]="{mask:'971000000000', len:12}" required></ion-input>
</ion-item>
<p *ngIf="mobileNumber.errors.pattern" class="danger" padding>Phone number is not valid.</p>
</ion-col>
<ion-col style="padding: 0px;">
<ion-item>
<ion-input type="text" formControlName="email" placeholder="{{lang.Labels.Email}}" name="email" [(ngModel)]="register.email" required></ion-input>
</ion-item>
<p *ngIf="email.errors.pattern" class="danger" padding>Email is not valid.</p>
</ion-col>
<div class="row row-no-padding div_right">
<div class="col text-right">
<button ion-button class="submit-btn" full type="submit" [disabled]="!registerForm.form.valid">{{lang.Buttons.next}}</button>
</div>
</div>
这是.ts文件
import {NgForm, FormGroup, FormControl, Validators,FormBuilder } from
'@angular/forms'
mobnumPattern = "^((\\+971-?)|0)?[0-9]{10}$";
emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
registerForm: FormGroup;
constructor(private formBuilder:FormBuilder) {
this.registerForm = new FormGroup({
mobileNumber: new FormControl('', Validators.pattern(this.mobnumPattern)),
email: new FormControl('', Validators.pattern(this.emailPattern))
});
}
答案 0 :(得分:0)
尝试以下代码:
将[ngModelOptions]
设置为true
,例如:
[ngModelOptions]="{standalone: true}"
或定义您的FormGroup
,例如:
const registerForm = new FormGroup({
mobileNumber: new FormControl('', Validators.pattern(this.mobnumPattern)),
email: new FormControl('', Validators.pattern(this.emailPattern))
});
并在HTML中删除name
和[(ngModel)]
属性