我有很多字段,如
firstName
、lastName
等,这些字段是从后端制作的required
。如果我提交表单而不填写名字,则会在网络预览中引发以下错误。如果我填满 firstName
并将 lastName
留空,则会抛出另一个错误:网络预览中的 lastName is required
:
{
"status": "failed",
"error": {
"message": "Invalid request data. Please review the request and try again.",
"code": [
{
"message": "firstName is required",
"code": "any.required"
}
]
}
}
HTML:
<input type="text" class="form-control" [(ngModel)]="registration.firstName">
<input type="text" class="form-control" [(ngModel)]="registration.lastName">
<button type="button" class="btn btn-success" (click)="createRegistration(registration)">Submit</button>
我只是想在有人尝试单击页面上某处的
Submit
按钮时抛出网络预览中所示的错误消息:
<p>firstName is required</p>
TS:
createRegistration(registration:StudentRegistration){
this.coreService.addRegistration(registration).subscribe({
next: (res: any) => {
this.registration = res.data || {} as StudentRegistration;
this.opd.registration = res.data._id;
this.createOpdStudent()
},
error: (err) => {
console.log(err);
}
})
}
我在 Angular 中看过很多前端验证教程,但这太费力了,因为我必须验证前端中的每个字段
again
。我找不到像我这样的后端验证教程。
PS:我不想使用工作前端方法,因为有多个表单具有数百个字段
<p *ngIf="registration.firstName == '' || registration.firstName == undefined">First name is compulsory</p>
在
error
回调中,您可以提取如下错误消息:
errorMessages: string[] = [];
error: (err) => {
console.log(err);
let errorResponse = err.error;
this.errorMessages = errorResponse.code.map((x: any) => x.message);
}
显示
errorMessages
组:
<div *ngFor="let errorMessage of errorMessages">
{{ errorMessage }}
</div>