我想根据用户类型显示不同的字段,并根据用户类型有条件地进行表单验证。我不想为每种类型的用户创建单独的表单。用户白金用户有三种,黄金用户和普通用户。
.ts文件的代码
this.signupForm = this.formBuilder.group(
{
mobileNumber: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern(this.regExNumberCell),
])
),
confermPassword: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern(this.regExPassword),
])
),
surName: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern(this.regExsurName),
])
),
email: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern(this.regExEmail),
])
),
name: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern(this.regExName),
])
),
password: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern(this.regExPassword),
])
),
},
{ validator: this.passwordsMatchValidator }
);
答案 0 :(得分:0)
您可以按以下条件创建带有验证的表单:
在您的.ts文件中
if (user === 'normal') {
// Inside this clause put the validation logic for normal user and make the fields required and optional according to your requirement
this.signupForm = this.formBuilder.group(
{
mobileNumber: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern(this.regExNumberCell),
])
),
}
// ....
);
}
else if (user === 'gold') {
// Inside this clause put the validation logic for gold user and make the fields required and optional according to your requirement
this.signupForm = this.formBuilder.group(
{
mobileNumber: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern(this.regExNumberCell),
])
), // ....
}
);
}
else if (user === 'platinum') {
// Inside this clause put the validation logic for platinum user and make the fields required and optional according to your requirement
this.signupForm = this.formBuilder.group(
{
mobileNumber: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern(this.regExNumberCell),
])
), // ....
}
);
}
在.html文件中,您可以根据用户类型显示和隐藏字段,例如:
<ng-container *ngIf="user!== 'gold'">
<ion-label class="inputTitle-label">Username</ion-label>
<div class="input-container">
<ion-input
class="input"
formControlName="username"
autocomplete="off"
type="text"
required
></ion-input>
</div>