My app is developed with Angular 9, and I have some additional functions needed:
So app looks like that:
component.ts:
ngOnInit() {
this.buildForm()
}
get f() {
return this.form.controls
}
buildForm() {
this.form = this.fb.group({
input: [null, [Validators.pattern('^[a-z][a-z0-9_]+$')]]
})
}
component.html
<div *ngIf="f.input.errors.pattern">error message</div>
ISSUE:
There is multiply RegExp conditions: ^[a-z][a-z0-9_]+$
Is there any way to display error messages for every condition?
e.g.:
Validators.pattern([{'firstLetter': '^[a-z]'}, {'symbols': '^[a-z][a-z0-9_]+$'}])
UPDATE #1
According to this SO answer, I tried change code to this, but I cannot handle error with *ngIf:
component.ts
regexValidator(regex: RegExp, error: ValidationErrors): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
if (!control.value) {
return null;
}
const valid = regex.test(control.value);
return valid ? null : error;
}
}
buildForm() {
this.form = this.fb.group({
login: [null, [
this.regexValidator(new RegExp('^[a-z]+$'), {'firstLetter': ''}),
this.regexValidator(new RegExp('^[a-z][a-z0-9_]+$'), {'symbols': ''})
]],
})
}
component.html:
<div *ngIf="f.login.hasError('firstLetter')">error message</div>
<div *ngIf="f.login.hasError('symbols')">error message</div>
SOLUTION:
Change empty string to true of sting with value:
this.regexValidator(new RegExp('^[a-z]+$'), {'firstLetter': true})