Atelier 2 : Création et Validation d’un Formulaire

lancer powershelle en mode Administrateur puis tapez cette commande) : Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

1️⃣ Créer un nouveau projet Angular

ng new creation-compte --standalone --style=css --routing=false
      
    

2️⃣ Aller dans le dossier du projet

cd creation-compte
      
    

3️⃣ Installer Bootstrap

npm install bootstrap
      
    

➡️ Puis ajouter dans angular.json :

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
]
      
    

4️⃣ Créer le fichier app.component.html

<div class="d-flex justify-content-center align-items-center min-vh-100 bg-light">
  <div class="card shadow-lg p-4 w-100" style="max-width: 500px;">
    <div class="text-center mb-3">
      <img src="https://dummyimage.com/200x80/007bff/ffffff&text=LOGO" 
           alt="Logo Entreprise" class="img-fluid" style="max-height: 80px;">
    </div>
    <h3 class="text-center mb-4">Créer un compte</h3>

    <div *ngIf="success" class="alert alert-success alert-dismissible fade show" role="alert">
      <strong>Félicitations !</strong> Votre compte a été créé avec succès !
      <button type="button" class="btn-close" aria-label="Close" (click)="closeAlert()"></button>
    </div>

    <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
      <div class="mb-3">
        <label class="form-label">Nom complet</label>
        <input type="text" formControlName="fullName" class="form-control">
        <small class="text-danger" *ngIf="f['fullName'].invalid && f['fullName'].touched">
          Nom complet requis (min. 3 caractères).
        </small>
      </div>

      <div class="mb-3">
        <label class="form-label">Nom d'utilisateur</label>
        <input type="text" formControlName="username" class="form-control">
        <small class="text-danger" *ngIf="f['username'].invalid && f['username'].touched">
          Nom d'utilisateur requis.
        </small>
      </div>

      <div class="mb-3">
        <label class="form-label">Email</label>
        <input type="email" formControlName="email" class="form-control">
        <small class="text-danger" *ngIf="f['email'].invalid && f['email'].touched">
          Email valide requis.
        </small>
      </div>

      <div class="mb-3">
        <label class="form-label">Téléphone</label>
        <input type="tel" formControlName="phone" class="form-control" placeholder="+221770000000">
        <small class="text-danger" *ngIf="f['phone'].invalid && f['phone'].touched">
          Numéro requis au format international (+221...).
        </small>
      </div>

      <div class="mb-3">
        <label class="form-label">Mot de passe</label>
        <input type="password" formControlName="password" class="form-control">
        <small class="text-danger" *ngIf="f['password'].errors?.['pattern'] && f['password'].touched">
          Min. 8 caractères, avec 1 majuscule, 1 chiffre et 1 caractère spécial.
        </small>
      </div>

      <div class="mb-3">
        <label class="form-label">Confirmer mot de passe</label>
        <input type="password" formControlName="confirmPassword" class="form-control">
        <small class="text-danger" *ngIf="registerForm.errors?.['passwordMismatch'] && f['confirmPassword'].touched">
          Les mots de passe ne correspondent pas.
        </small>
      </div>

      <button class="btn btn-primary w-100" type="submit" [disabled]="registerForm.invalid">
        Créer le compte
      </button>
    </form>
  </div>
</div>
      
    

5️⃣ Créer le fichier app.component.ts


        
    import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  registerForm: FormGroup;
  success = false;

  constructor(private fb: FormBuilder) {
    this.registerForm = this.fb.group({
      fullName: ['', [Validators.required, Validators.minLength(3)]],
      username: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.email]],
      phone: ['', [Validators.required, Validators.pattern(/^\+\d{10,15}$/)]],
      password: ['', [
        Validators.required,
        Validators.minLength(8),
        Validators.pattern(/^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])/)
      ]],
      confirmPassword: ['', Validators.required]
    }, { validators: this.passwordMatchValidator });
  }

  get f() {
    return this.registerForm.controls;
  }

  passwordMatchValidator(form: FormGroup) {
    const pass = form.get('password')?.value;
    const confirm = form.get('confirmPassword')?.value;
    return pass === confirm ? null : { passwordMismatch: true };
  }

  onSubmit() {
    if (this.registerForm.valid) {
      this.success = true;
      console.log('Compte créé :', this.registerForm.value);
      this.registerForm.reset();
    }
  }

  closeAlert() {
    this.success = false;
  }
}


        
        
    
      
    

6️⃣ Créer le fichier app.component.css

body {
  background-color: #f8f9fa;
}

.card {
  border-radius: 12px;
}

button {
  font-weight: bold;
}
      
    

7️⃣ Modifier main.ts

import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { importProvidersFrom } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

bootstrapApplication(AppComponent, {
  providers: [importProvidersFrom(ReactiveFormsModule)]
}).catch(err => console.error(err));