I am currently working on implementing form validation in my project. I have created a basic login form and now I want to validate the input fields before submitting them to the server, while also providing visual feedback to the user if the inputs are invalid. I attempted to follow the guidelines outlined in the official documentation, but encountered some challenges.
Here is the code snippet that I have developed so far:
<div class="content">
<section>
<div class="form-wrapper">
<h3>Register</h3>
<form class="form" [formGroup]="form" (submit)="submit()">
<div class="form-item">
<input type="text" formControlName="name" placeholder="Name" required>
</div>
<div class="form-item">
<input formControlName="email" type="email" placeholder="Email Address" required>
</div>
<div class="form-item">
<input formControlName="password" type="password" placeholder="Password" required>
</div>
<div class="form-item">
<button type="submit">Register</button>
</div>
</form>
</div>
</section>
</div>
Additionally, here is the corresponding component.ts file:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { AuthService } from 'src/app/services/auth.service';
import { Router } from '@angular/router';
import { Validators } from '@angular/forms';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
form: FormGroup;
name: string = '';
email: string = '';
password: string = '';
error: string = '';
constructor( private auth: AuthService, private router: Router) { }
ngOnInit(): void {
this.form = new FormGroup({
name: new FormControl(this.name,[
Validators.required,
]),
email: new FormControl(this.email,[
Validators.required,
Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")
]),
password: new FormControl(this.password, [
Validators.required,
Validators.minLength(8)
])
})
}
submit(){
this.auth.tryRegister(this.form.getRawValue())
.subscribe(
res => {
if(res.status == 200){
this.router.navigate(['/verify'])
}},
err => {
if(err.status == 400){
this.error = 'Invalid form data'
}
else if(err.status == 401){
this.error = 'email address already in use'
}
})
}
}
In order to visually indicate an invalid email address, I would like to apply the styling of my custom class ".is-invalid", which adds a red border around the input tag. If there are any existing Angular CSS classes for achieving this effect, I would be open to utilizing them as well.
As I am relatively new to Angular development, any guidance or recommended resources for accomplishing this task properly would be greatly appreciated.
Edit: I have implemented getters for my properties, but I am still encountering issues. Whenever I attempt to check
*ngIf="name.errors?.required"
, I receive the error "object is possibly null", despite using the safe navigation operator ?.