minlength和maxlength,角度误差验证


this.employeeForm = this.fb.group({
fullName: [
'',
[
Validators.required,
Validators.minLength(2),
Validators.maxLength(10),
],
],
email: [''],
skills: this.fb.group({
skillName: [''],
experienceInYears: [''],
proficiency: [''],
}),
});

我使用反应形式(角度(进行验证和错误展示。但为了显示错误消息,用户输入的输入不在最小和最大标准之间,我面临着问题。

<div class="col-sm-8">
<input
id="fullName"
type="text"
class="form-control"
formControlName="fullName"
/>
<p
*ngIf="
employeeForm.get('fullName')?.invalid &&
employeeForm.get('fullName')?.touched
"
>
please enter the valid full name
</p>
<p *ngIf="employeeForm.get('fullName')?.errors">  <-- I am not able to access the minLength and maxLength after errors , therefore not able to show case the error message also
Full name should be under min and max
</p>
</div>
</div>

如何在最小和最大长度出现错误的情况下显示错误。就像employeeForm.get('fullName')?.errors. no minLength / maxLenth之后一样,什么都没有发生。

提前感谢

Toof_LD的答案很好,但如果您想考虑实现更多可重用的代码,请查看自定义验证器。它们非常易于使用,一旦创建,就可以在应用程序中的任何位置使用。当然,当有大量代码检查验证(例如在HTML中(或需要执行更高级的验证时,建议使用此解决方案。

总的来说,语法非常简单。

没有参数的自定义验证器的语法:

function customValidator(control: AbstractControl): {[key: string]: boolean} | null {
if(sthWrong) {
return { yourValidatorName: true};
}

return null;
}

带参数的验证器的语法:

function customValidatorWithParameters(parameters: any): ValidatorFn {
return(control: AbstractControl): {[key: string]: boolean} | null {
if(sthWrong) {
return { yourValidatorName: true};
}

return null;
}
}

最棒的是,这一切都归结为在HTML中检查控件是否有效(例如通过true或false值(。下面是一个带有参数的自定义验证器的简单使用示例。https://stackblitz.com/edit/angular-ivy-4tfvfd?file=src/app/app.component.ts

试试这个:

  • 在.ts文件中:
get formControl(){
return this.employeeForm.controls;
}
表单模板中的
<div class="col-sm-8">
<input
id="fullName"
type="text"
[ngClass]="{'is-invalid': isSubmitted && formControl.fullName.errors}"
class="form-control"
formControlName="fullName"
/>
<div class="invalid-feedback"
*ngIf="isSubmitted && formControl.fullName.errors">
<ng-container *ngIf="formControl.fullName.errors.minLength || formControl.fullName.errors.maxLength ">
please enter the valid full name
</ng-container>
</div>
</div>

您应该使用maxlength而不是maxLength

最新更新