FormGroup.controls 在自定义验证程序中未定义



我有一个带有html页面的Ionic Project。该页面具有以下形式:

<form [formGroup]="configureLeagueForm">
<ion-item>
<ion-label  position="floating">TEXT</ion-label>
<ion-input type="number" formControlName="roundsQuantity" ></ion-input>
</ion-item>
<ion-item *ngIf="!configureLeagueForm.controls.roundsQuantity.valid  && (configureLeagueForm.controls.roundsQuantity.dirty || submitAttempt)">
<p [class.invalid]="!configureLeagueForm.controls.roundsQuantity.valid  && (configureLeagueForm.controls.roundsQuantity.dirty || submitAttempt)" >TEXT IF ERROR .</p>
</ion-item>
</form>

和 .ts 文件

this.configureLeagueForm = this.formBuilder.group({
roundsQuantity: [1, Validators.compose([Validators.min(1), Validators.max(100), ConfigureChampionshipFormValidator.roundsQuantity])],
});

现在,我的验证人

export class ConfigureChampionshipFormValidator {
static roundsQuantity(group: FormGroup) : any{
var roundsQuantity = group.controls['roundsQuantity'].value;
if(String(roundsQuantity).trim() == ""){ // Just an example of validation
group.controls['roundsQuantity'].setErrors({"mandatory_error": true});
return { "mandatory_error": true };      
} else{
return { "mandatory_error": false }; 
}
}
}

但是在代码的这一步:

group.controls['roundsQuantity'].value

我有未定义的组控件。

这发生在我打开页面时。

您的验证器设置在FormControl(roundsQuantity(。因此,它将作为参数接收的是表单控件。不是其父窗体组。

您有一些问题,如其他答案中所述,您的自定义验证器正在接收表单控件,而不是整个组。

其次,如果值通过验证,自定义验证程序应返回nullnull在验证器中被视为有效。因此,请将您的自定义验证器更改为:

export class ConfigureChampionshipFormValidator {
static roundsQuantity(roundsQuantity: AbstractControl): any {
if (!roundsQuantity.value) {
return { "mandatory_error": true };
} 
return null;
}
}

纯角度演示

最新更新