Implement error handling for the create qualification form #19

Merged
ptran merged 9 commits from feature/validation into main 2025-01-08 10:31:38 +00:00
2 changed files with 38 additions and 5 deletions
Showing only changes of commit 3d1750ecec - Show all commits

View File

@ -1,5 +1,22 @@
<form [formGroup]="qualificationForm" (ngSubmit)="create()">
<label for="skill-input">Skill</label>
<input id="skill-input" type="text" formControlName="skill">
<button type="submit">create</button>
<!-- create-qualification.component.html -->
<form [formGroup]="qualificationForm" (ngSubmit)="create()" class="space-y-4">
<div>
<label for="skill-input" class="block mb-1">Skill</label>
<input
id="skill-input"
type="text"
formControlName="skill"
class="w-full p-2 border rounded"
[ngClass]="{'border-red-500 focus:ring-0 focus:outline-none': isFieldInvalid('skill')}">
<div
*ngIf="isFieldInvalid('skill')"
class="text-sm text-red-500 mt-1">
{{ getErrorMessage('skill') }}
</div>
</div>
<button type="submit">
Create
</button>
</form>

View File

@ -2,11 +2,14 @@ import {Component, inject} from '@angular/core';
import {FormBuilder, ReactiveFormsModule, Validators} from "@angular/forms";
import QualificationService from "../services/qualification.service";
import {MatDialogRef} from "@angular/material/dialog";
import {NgClass, NgIf} from "@angular/common";
@Component({
selector: 'app-create-qualification',
imports: [
ReactiveFormsModule
ReactiveFormsModule,
NgClass,
NgIf
],
templateUrl: './create-qualification.component.html',
styleUrl: './create-qualification.component.css'
@ -20,6 +23,19 @@ export class CreateQualificationComponent {
'skill': ['', Validators.required],
});
isFieldInvalid(fieldName: string): boolean {
const field = this.qualificationForm.get(fieldName);
return !!field?.invalid && (field.dirty || field.touched);
}
getErrorMessage(fieldName: string): string {
const field = this.qualificationForm.get(fieldName);
if (field?.errors?.['required']) {
return 'This field is required';
}
return '';
}
create() {
if (!this.qualificationForm.valid) {
console.error('Validation failed');