π― Form Validation in Angular Template Forms
Validation: Because Users Love Making Mistakes! π
Ever filled out a form and got an error? Yep, weβre here to make sure those mistakes get caught before they cause chaos! Letβs dive into form validation in Angular template-driven forms.
π Step 1: Set Up the HTML Form
Modify app.component.html
to create a template form with validation:
<h1>Template Form Validation</h1>
<form #userForm="ngForm">
<div class="card">
<label>First Name</label>
<input type="text" [(ngModel)]="userObj.fName" #fname="ngModel"
name="fName" required><br><br>
<div class="text-danger">
<span *ngIf="fname.errors?.['required'] && fname.touched">
This is Required<br><br></span>
</div>
<label>Last Name</label>
<input type="text" [(ngModel)]="userObj.lName" #lname="ngModel"
name="lName" required minlength="5"><br><br>
<div class="text-danger">
<span *ngIf="lname.errors?.['required'] &&
lname.touched">This is Required<br><br></span>
<span *ngIf="lname.errors?.['minlength'] &&
lname.touched">Minimum Length: 5 characters<br><br></span>
</div>
<label>Email</label>
<input type="email" [(ngModel)]="userObj.email"
#Email="ngModel" name="email" required><br><br>
<div class="text-danger">
<span *ngIf="Email.errors?.['required'] &&
Email.touched">This is Required<br><br></span>
<span *ngIf="Email.errors?.['email']">
Enter a valid email format! π§<br><br></span>
</div>
<button type="submit" [disabled]="userForm.invalid"
(click)="onSave()">Submit</button>
</div>
</form>
π΄ Validation Rules:
- First Name: Required
- Last Name: Required, at least 5 characters
- Email: Required, must be a valid email
- Submit button only works when the form is valid π
π» Step 2: Modify app.component.ts
Letβs handle the form data:
import { NgIf } from '@angular/common';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [FormsModule, NgIf],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'formvalid';
userObj: any = {
fName: '',
lName: '',
email: ''
}
onSave(){
console.log("Form Submitted! π", this.userObj);
}
}
π― When the form is submitted, it logs the data. (Replace console.log
with a real API call if needed!)
π¨ Step 3: Styling It Up! (Because Ugly Forms Suck π)
Modify app.component.css
:
.card {
flex: auto;
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
background-color: aquamarine;
padding: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.text-danger {
color: red;
}
π This makes our form look less boring and adds a light shadow effect.
π₯ Summary
β We built a template-driven form with validation. β We added error messages that show up when users mess up. β We made sure the submit button is disabled unless everything is valid. β We styled the form to look nice and clean!
π Congratulations! Now your forms are smarter than ever. Keep coding and happy Angular-ing! ππ₯
No comments:
Post a Comment