<div *ngIf="usernameForm.errors?.['required']">
Name is required.
</div>
+ <div *ngIf="usernameForm.hasError('whitespace')">The username must not be empty</div>
</div>
</div>
<button type="submit" class="btn btn-primary" (click)="updateName()" [disabled]="usernameForm.invalid">Pick Name</button>
})
export class UserComponent {
- usernameForm = new FormControl('', Validators.required);
+ usernameForm = new FormControl('', [ Validators.required, this.noWhitespaceValidator ]);
updateName(): void {
var input = this.usernameForm.getRawValue();
if (input !== null) {
- this.userService.setUser(input);
+ this.userService.setUser(input.trim());
this.router.navigate(['chatrooms'])
}
}
+ noWhitespaceValidator(control: FormControl) {
+ const isWhitespace = (control.value || '').trim().length === 0;
+ const isValid = !isWhitespace;
+ return isValid ? null : { 'whitespace': true };
+ }
+
constructor(
private userService: UserService,
private router: Router) {}