[英]Having trouble with validation error messages in Angular
I am having trouble with error messages in my validation.我在验证时遇到错误消息。 I want to be able to differentiate between the different errors with different messages.我希望能够区分不同消息的不同错误。 How can I fix this.我怎样才能解决这个问题。 Here is my typescript function:这是我的 typescript function:
createFormControl(){
this.updatedArray.forEach((element: any) => {
element.maxlength = +element.maxlength
if(element.required === "true"){
this.xmlForm.addControl(element.name, new FormControl('',[Validators.required, Validators.maxLength(element.maxlength)]));
}else{
this.xmlForm.addControl(element.name, new FormControl(''));
}
});
console.log(this.xmlForm)
}
Here is and example of a part of my HTML:这是我的 HTML 的一部分的示例:
<div class="row pb-2" [formGroup]="xmlForm">
<div class="col-lg-4" *ngFor="let form of updatedArray">
<div class="form-group" [ngSwitch]="form.type">
<div *ngSwitchCase="'string'">
<label _ngcontent-emf-c46="" for="input1">{{form.name}}</label>
<input _ngcontent-emf-c46="" type="text" [formControlName]="form.name" placeholder="" id="input1" aria-describedby="Text field"
name="name" class="form-control ng-untouched ng-pristine ng-valid" ng-reflect-name="name"
ng-reflect-model="">
<div *ngIf="xmlForm.get(form.name).dirty || xmlForm.get(form.name).touched">
<small class="error" *ngIf="!xmlForm.get(form.name).valid">
{{form.name}} is Required
</small>
</div>
<div *ngIf="xmlForm.get(form.name).dirty">
<small class="error" *ngIf="!xmlForm.get(form.name).valid">
Max Length is {{form.maxlength}}
</small>
</div>
</div>
Both error messages are popping up when one or the other is true.当其中一个为真时,两个错误消息都会弹出。 I just want one showing up.我只想要一个出现。 How can I fix this?我怎样才能解决这个问题?
Instead of *ngIf=".xmlForm.get(form.name).valid"
to check for max length compliance, you should try *ngIf="xmlForm.get(form.name).errors?.maxlength"
.而不是*ngIf=".xmlForm.get(form.name).valid"
来检查最大长度合规性,您应该尝试*ngIf="xmlForm.get(form.name).errors?.maxlength"
。 According to the Angular API , the maxlength
property becomes available in the errors
map if the specified max length is exceeded.根据Angular API ,如果超过指定的最大长度,则maxlength
属性在errors
map 中可用。 You can do a similar check for required using *ngIf="xmlForm.get(form.name).errors?.required"
您可以使用*ngIf="xmlForm.get(form.name).errors?.required"
对 required 进行类似的检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.