🎯 React Form Validation (Because Forms Need Rules!)
Angular isn’t the only one that needs validation—React does too! Let’s build a React Form with validation using ReactiveFormsModule
. 🏗️
🚀 Step 1: Set Up app.component.ts
Modify app.component.ts
to create a React-based form:
import { ReactiveFormsModule, Validators } from '@angular/forms';
import {Component} from '@angular/core';
import {FormGroup, FormControl} from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'reactform';
profileForm = new FormGroup({
firstName: new FormControl('', [Validators.required]),
lastName: new FormControl('', [Validators.required, Validators.minLength(5)]),
email: new FormControl('', [Validators.required, Validators.email]),
street: new FormControl(''),
city: new FormControl(''),
state: new FormControl('Tamil Nadu'),
zip: new FormControl(''),
});
}
🎨 Step 2: Create the Form in app.component.html
Modify app.component.html
to include input fields and validation:
<h1>Reactive Form & Validation</h1>
<form [formGroup]="profileForm" (ngSubmit)="onUserSave()">
<label>First Name: </label>
<input type="text" formControlName="firstName">
<div class="text-danger" *ngIf="profileForm.controls['firstName'].errors?.['required']">This is Required</div>
<label>Last Name: </label>
<input type="text" formControlName="lastName">
<div class="text-danger" *ngIf="profileForm.controls['lastName'].errors?.['required']">This is Required</div>
<div class="text-danger" *ngIf="profileForm.controls['lastName'].errors?.['minlength']">Minimum Length: 5 characters</div>
<label>Email: </label>
<input type="email" formControlName="email">
<div class="text-danger" *ngIf="profileForm.controls['email'].errors?.['required']">Email is required</div>
<button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>
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 React-based form with validation. ✅ Required fields and error messages are handled. ✅ Submit button only works when everything is correct.
💡 Now your React forms are smarter than ever! Keep coding and happy React-ing! 🚀🔥
No comments:
Post a Comment