feat: add email format validator and switch RegisterComponent to ReactiveFormsModule

This commit is contained in:
Chneemann 2025-05-06 09:06:23 +02:00
parent de381bf5b9
commit c049f29407
4 changed files with 123 additions and 101 deletions

View file

@ -10,54 +10,50 @@
<a routerLink="/login">To the login</a>
</div>
} @else {
<form
#registerForm="ngForm"
(ngSubmit)="onSubmit(registerForm)"
onsubmit="return false"
[formGroup]="form"
(ngSubmit)="onSubmit()"
(input)="this.errorService.clearError()"
>
<div class="mail-field">
<input
type="mail"
formControlName="mail"
type="email"
id="mail"
name="mail"
#mail="ngModel"
placeholder="Email Address"
autocomplete="email"
[(ngModel)]="authData.mail"
[class.error-border]="
(!mail.valid && mail.touched) ||
(mail.touched &&
!isUserEmailValid(authData.mail) &&
authData.mail.length > 0)
form.controls['mail'].invalid && form.controls['mail'].touched
"
required
/>
<img class="mail-icon" src="./assets/img/mail.svg" />
</div>
<div class="error-container">
@if (form.controls['mail'].touched && form.controls['mail'].invalid) {
<div class="error-msg">
@if (!mail.valid && mail.touched) {
<p>Please enter your email</p>
} @else { @if (mail.touched && authData.mail.length > 0 &&
!isUserEmailValid(authData.mail)) {
<p>This is not a valid email format</p>
}}
@if (form.controls['mail'].errors?.['required']) {
<p role="alert">Please enter your email</p>
} @if (form.controls['mail'].errors?.['invalidEmailFormat']) {
<p role="alert">This is not a valid email format</p>
}
</div>
}
</div>
<div class="password-field">
<input
[type]="authService.passwordFieldType"
id="password"
name="password"
#password="ngModel"
formControlName="password"
placeholder="Enter a password"
autocomplete="new-password"
[(ngModel)]="authData.password"
pattern="[^<>]*"
minlength="6"
minlength="8"
[class.error-border]="
password.invalid && password.touched && authData.password.length < 6
form.controls['password'].invalid &&
form.controls['password'].touched
"
required
/>
<img class="password-icon" src="./assets/img/password.svg" />
<img
@ -66,31 +62,32 @@
[src]="authService.passwordIcon"
/>
</div>
<div class="error-container">
@if (form.controls['password'].touched &&
form.controls['password'].invalid) {
<div class="error-msg">
@if (!password.valid && password.touched && authData.password.length <
1) {
<p>Please enter a password</p>
} @else { @if (authData.password && authData.password.length < 6 &&
password.touched) {
<p>Password is too short, min 6 characters</p>
} }
@if (form.controls['password'].errors?.['required']) {
<p role="alert">Please enter a password</p>
} @if (form.controls['password'].errors?.['minlength']) {
<p role="alert">Password is too short, min 8 characters</p>
}
</div>
}
</div>
<div class="password-field">
<input
[type]="authService.passwordFieldType"
id="passwordConfirm"
name="passwordConfirm"
#passwordConfirm="ngModel"
formControlName="passwordConfirm"
placeholder="Confirm password"
autocomplete="new-password"
[(ngModel)]="authData.passwordConfirm"
pattern="[^<>]*"
minlength="6"
minlength="8"
[class.error-border]="
authData.password !== authData.passwordConfirm &&
passwordConfirm.touched
form.controls['passwordConfirm'].invalid &&
form.controls['passwordConfirm'].touched
"
required
/>
<img class="password-icon" src="./assets/img/password.svg" />
<img
@ -99,37 +96,35 @@
[src]="authService.passwordIcon"
/>
</div>
<div class="error-container">
@if ( form.controls['passwordConfirm'].touched &&
form.controls['passwordConfirm'].invalid ) {
<div class="error-msg">
@if (authData.password !== authData.passwordConfirm &&
passwordConfirm.touched) {
@if (form.controls['passwordConfirm'].errors?.['required']) {
<p>Please confirm your password</p>
} @if ( form.controls['password'].value !==
form.controls['passwordConfirm'].value &&
form.controls['passwordConfirm'].touched ) {
<p>The passwords do not match</p>
}
</div>
}
</div>
<div class="checkbox">
<label class="container"
>I agree to the&nbsp;
<label class="container">
I agree to the&nbsp;
<a routerLink="/privacy-policy">Privacy policy</a>.
<input
type="checkbox"
id="checkbox"
name="checkbox"
#checkbox
[(ngModel)]="authData.privacyPolicy"
/>
<input type="checkbox" formControlName="privacyPolicy" />
<span class="checkmark"></span>
</label>
</div>
<app-btn-large
[value]="'Get Started'"
[disabled]="
(!isUserEmailValid(authData.mail) &&
authData.mail &&
authData.mail.length > 0) ||
authData.password !== authData.passwordConfirm ||
!authData.password ||
!authData.passwordConfirm ||
!authData.privacyPolicy ||
authData.send
form.invalid || form.controls['privacyPolicy'].value === false
"
></app-btn-large>
</form>

View file

@ -1,34 +1,41 @@
import { Component, OnInit } from '@angular/core';
import { BtnLargeComponent } from '../../../shared/components/buttons/btn-large/btn-large.component';
import { FormsModule, NgForm } from '@angular/forms';
import {
FormBuilder,
FormGroup,
FormsModule,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { CommonModule } from '@angular/common';
import { AuthService } from '../../../services/auth.service';
import { ErrorService } from '../../../services/error.service';
import { emailFormatValidator } from '../../../validators/email-format.validator';
@Component({
selector: 'app-register',
standalone: true,
imports: [CommonModule, BtnLargeComponent, FormsModule, RouterLink],
imports: [
CommonModule,
BtnLargeComponent,
FormsModule,
ReactiveFormsModule,
RouterLink,
],
templateUrl: './register.component.html',
styleUrl: './register.component.scss',
})
export class RegisterComponent implements OnInit {
registrationSuccess: boolean = false;
authData = {
mail: '',
password: '',
passwordConfirm: '',
privacyPolicy: false,
send: false,
};
form: FormGroup = new FormGroup({});
/**
* Initializes the RegisterComponent with ActivatedRoute, AuthService, and ErrorService.
* Initializes the RegisterComponent with ActivatedRoute, FormBuilder, AuthService, and ErrorService.
*/
constructor(
private route: ActivatedRoute,
private fb: FormBuilder,
public authService: AuthService,
public errorService: ErrorService
) {}
@ -37,68 +44,69 @@ export class RegisterComponent implements OnInit {
* Initializes the component by setting up necessary data.
*/
ngOnInit(): void {
this.createRegisterForm();
this.setEmailFromQueryParams();
}
/**
* Initializes the registration form with required fields and validators.
*/
private createRegisterForm(): void {
this.form = this.fb.group({
mail: ['', [Validators.required, emailFormatValidator()]],
password: ['', Validators.required],
passwordConfirm: ['', Validators.required],
privacyPolicy: [false, Validators.requiredTrue],
});
}
/**
* Sets the email address from the query parameters in the URL.
*/
private setEmailFromQueryParams(): void {
this.route.queryParams.subscribe((params) => {
this.authData.mail = params['mail'] || '';
const email = params['mail'] || '';
this.form.patchValue({ mail: email });
});
}
/**
* Validates the given email address.
* Converts to lowercase before checking against the regex.
* Handles the submission of the registration form.
*
* @param emailValue The email address to validate.
* @returns True if the email format is valid, false otherwise.
* @returns A Promise that resolves when the registration process is complete.
*/
isUserEmailValid(emailValue: string): boolean {
const emailRegex = /^[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
return emailRegex.test(emailValue.toLowerCase());
}
/**
* Handles form submission for user registration.
* Sends registration request and handles success/error responses.
*
* @param ngForm The registration form instance.
*/
async onSubmit(ngForm: NgForm): Promise<void> {
if (ngForm.submitted && ngForm.form.valid) {
async onSubmit(): Promise<void> {
if (this.form.valid) {
const body = this.createRegistrationRequestBody();
this.authData.send = true;
this.form.disable();
try {
await this.authService.register(body);
ngForm.resetForm();
this.form.reset();
this.registrationSuccess = true;
this.errorService.clearError();
} catch (error) {
this.authData.send = false;
this.form.enable();
this.errorService.handleError(error);
}
}
}
/**
* Creates the request body for the registration API.
* Constructs the registration request payload from form values.
*
* @returns The registration request body.
* @returns An object containing the email (lowercased), username (from email), and password.
*/
private createRegistrationRequestBody(): {
email: string;
username: string;
password: string;
} {
const formValue = this.form.value;
return {
email: this.authData.mail.toLowerCase(),
username: this.authData.mail.split('@')[0],
password: this.authData.password,
email: formValue.mail.toLowerCase(),
username: formValue.mail.split('@')[0],
password: formValue.password,
};
}
}

View file

@ -0,0 +1,11 @@
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function emailFormatValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const email = control.value;
const emailRegex = /^[\w.%+-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
const isValid = emailRegex.test(email?.toLowerCase());
return isValid ? null : { invalidEmailFormat: true };
};
}

View file

@ -47,6 +47,14 @@ form {
}
}
.error-container {
display: flex;
align-items: center;
justify-content: center;
height: 24px;
padding: 9px;
}
.error-msg {
display: flex;
align-items: center;