There are several fields such as firstName
and lastName
that are marked as required
on the backend. If the form is submitted without entering the firstName, an error is displayed in the Network Preview. Similarly, if the firstName is filled but the lastName is left empty, another error is shown: lastName is required
in the Network Preview:
{
"status": "failed",
"error": {
"message": "Invalid request data. Please review the request and try again.",
"code": [
{
"message": "firstName is required",
"code": "any.required"
}
]
}
}
Below is the 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>
I want to display the error message from the Network Preview when the Submit
button is clicked:
<p>firstName is required</p>
Here is the TypeScript code:
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);
}
})
}
I have explored frontend validation tutorials in Angular, but they require validating each field again
on the frontend. I am looking for a backend validation solution similar to my case.
PS: Avoiding the frontend method as there are numerous forms with hundreds of fields
<p *ngIf="registration.firstName == '' || registration.firstName == undefined">First name is compulsory</p>