I am trying to create a form validation. I have three fields: firstname
, password
, confirm_password
. Next to the name
field I try to display an error in span
that I need to fill in the name field, but it is shown to me immediately. Also, I'm trying to validate password storage, but it doesn't work for me
I have 2 questions: How can I make the error appear only when sending the form and not when typing the text and what do I do wrong when validating on matching passwords? Thanks
registration.component.ts
import { Component, OnInit } from '@angular/core';
import {AbstractControl, FormControl, FormGroup, Validators} from "@angular/forms";
@Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrls: ['./registration.component.css']
})
confirm_password_validator(control: AbstractControl) {
if (this.confirm_password.value != this.password.value) {
return {word: 'Паролі не збігаються'}
}
return null;
}
firstname = new FormControl('', [Validators.required, Validators.minLength(5)])
password = new FormControl('', [Validators.required, Validators.minLength(5)])
confirm_password = new FormControl('', [Validators.required, Validators.minLength(5), this.confirm_password_validator])
registrationForm: FormGroup = new FormGroup({
firstname: this.firstname,
password: this.password,
confirm_password: this.confirm_password
});
constructor() { }
ngOnInit(): void {}
}
registration.component.html
<form class="registration_form" [formGroup]="registrationForm">
<div class="different_input">
<span *ngIf="registrationForm.controls['firstname'].errors?.['required']">Field can't be empty</span>
<input type="text" placeholder="Type username..." [formControl]="firstname">
</div>
<div class="different_input">
<input type="password" placeholder="Create password..." [formControl]="password">
</div>
<div class="different_input">
<input type="password" placeholder="Confirm password..." [formControl]="confirm_password">
</div>
<button>Create</button>
</form>