feat: Added validation for the "Pick Name"-form
authorKai Moritz <kai@juplo.de>
Sun, 25 Dec 2022 21:35:36 +0000 (22:35 +0100)
committerKai Moritz <kai@juplo.de>
Sun, 25 Dec 2022 21:47:50 +0000 (22:47 +0100)
src/app/user/user.component.html
src/app/user/user.component.ts

index 6108608..b640cfd 100644 (file)
@@ -6,10 +6,18 @@
     <div class="form-group">
       <div class="input-group input-group-primary">
         <label for="name" class="input-group-addon">Username</label>
-        <input id="name" type="text" class="form-control" placeholder="Enter your username" [formControl]="name">
+        <input id="name" type="text" class="form-control" placeholder="Enter your username" [formControl]="usernameForm">
+      </div>
+      <div *ngIf="usernameForm.invalid && (usernameForm.dirty || usernameForm.touched)"
+           class="alert alert-danger">
+
+        <div *ngIf="usernameForm.errors?.['required']">
+          Name is required.
+        </div>
       </div>
     </div>
-    <button type="submit" class="btn btn-primary" (click)="updateName()">Pick Name</button>
+    <button type="submit" class="btn btn-primary" (click)="updateName()" [disabled]="usernameForm.invalid">Pick Name</button>
   </div>
 </div>
-<p>Value: {{ name.value }}</p>
+<p>Value: {{ usernameForm.value }}</p>
+<p>Form Status: {{ usernameForm.status }}</p>
index 7e3caeb..0ec3026 100644 (file)
@@ -1,5 +1,6 @@
 import { Component } from '@angular/core';
 import { FormControl } from '@angular/forms';
+import { Validators } from '@angular/forms';
 import { Router } from "@angular/router";
 import { UserService } from "../user.service";
 
@@ -10,10 +11,10 @@ import { UserService } from "../user.service";
 })
 export class UserComponent {
 
-  name = new FormControl('');
+  usernameForm = new FormControl('', Validators.required);
 
   updateName(): void {
-    var input = this.name.getRawValue();
+    var input = this.usernameForm.getRawValue();
     if (input !== null) {
       this.userService.setUser(input);
       this.router.navigate(['chatrooms'])