I am facing an issue with my form setup:
public initializeUserForm(user: User = null): void {
this.selectedUserForm = this.fb.group({
id: 0,
isActive: [true],
isSuperUser: [null],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
username: ['', [Validators.required, UniqueNameValidator(this.userNamesList, user)]],
password: ['',
Validators.pattern('^(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=\\D*\\d)[A-Za-z\\d!$%@#£€*?&]{8,}$')],
emailAddress: ['', Validators.email],
businessEmailAddress: ['', Validators.email],
address1: ['', Validators.maxLength(50)],
address2: ['', Validators.maxLength(50)],
city: ['', Validators.maxLength(30)],
stateProvince: ['', Validators.maxLength(30)],
postalCode: ['', Validators.maxLength(10)],
phoneNumber1: ['', Validators.maxLength(10)],
employeeId: [''],
notes: ['']
});
this.onFormChanges();
}
In addition to the form setup, I have a custom validator implemented as well:
import { Directive } from '@angular/core';
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
Directive({
selector: '[uniqueName]'
});
export function UniqueNameValidator(array: any[], exception = null): ValidatorFn {
const valObject = { nameDuplicate: true }
return (control: AbstractControl): ValidationErrors | null => {
if (exception) {
if (control.value === exception.name || control.value === exception.username) {
return array.findIndex(item => item.name === control.value || item.username === control.value) > 0 ? valObject : null;
} else {
return array.findIndex(item => item.name === control.value || item.username === control.value) > 0 ? valObject : null;
}
} else {
return array.findIndex(item => item.name === control.value || item.username === control.value) > 0 ? valObject : null;
}
};
}
Although the custom validation works correctly, it seems to interfere with the form's built-in functionality. The methods like this.selectedUserForm.touched or this.selectedUserForm.valid do not provide accurate results and always return False. What steps can I take to fix this issue without compromising the custom form validation?