mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-22 04:48:46 +00:00
fix(console): better error messages (#5409)
* fix(console): better error messages * fix: fix i18n error labels * rollout cnsl-i18n-errors * move errors to form-field * fix: form control errors * rollout validators * translate * replace variables * lint * self review * fix confirm validation * use help observable * fix validation errors * cleanup * custom validator for idp templates * lint * validate on blur * remove element --------- Co-authored-by: Max Peintner <[email protected]>
This commit is contained in:
co-authored by
Max Peintner
parent
e00cc187fa
commit
93e1fe0056
@@ -0,0 +1,20 @@
|
||||
<div class="cnsl-form-field-wrapper" (click)="_control.onContainerClick && _control.onContainerClick($event)">
|
||||
<ng-content select="cnsl-label"></ng-content>
|
||||
<div class="cnsl-rel" #inputContainer>
|
||||
<ng-content></ng-content>
|
||||
<ng-content select="cnslSuffix"></ng-content>
|
||||
</div>
|
||||
<ng-container *ngIf="help$ && help$ | async as help">
|
||||
<div [ngSwitch]="help.type" class="cnsl-form-field-subscript-wrapper">
|
||||
<div *ngSwitchCase="'hints'" class="cnsl-form-field-hint-wrapper" [@transitionMessages]="_subscriptAnimationState">
|
||||
<ng-content select="cnsl-hint"></ng-content>
|
||||
</div>
|
||||
<div *ngSwitchCase="'errors'" class="cnsl-form-field-error-wrapper" [@transitionMessages]="_subscriptAnimationState">
|
||||
<span cnslError *ngFor="let err of help.validationErrors">
|
||||
{{ err.i18nKey | translate : err.params }}
|
||||
</span>
|
||||
<ng-content select="cnsl-error"></ng-content>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
</div>
|
||||
+79
-17
@@ -10,6 +10,7 @@ import {
|
||||
HostListener,
|
||||
Inject,
|
||||
InjectionToken,
|
||||
Input,
|
||||
OnDestroy,
|
||||
QueryList,
|
||||
ViewChild,
|
||||
@@ -17,11 +18,10 @@ import {
|
||||
} from '@angular/core';
|
||||
import { NgControl } from '@angular/forms';
|
||||
import { MatLegacyFormFieldControl as MatFormFieldControl } from '@angular/material/legacy-form-field';
|
||||
import { Subject } from 'rxjs';
|
||||
import { startWith, takeUntil } from 'rxjs/operators';
|
||||
import { combineLatest, map, Observable, of, startWith, Subject, takeUntil } from 'rxjs';
|
||||
|
||||
import { CnslErrorDirective, CNSL_ERROR } from '../error/error.directive';
|
||||
import { cnslFormFieldAnimations } from './animations';
|
||||
import { CnslErrorDirective, CNSL_ERROR } from './error.directive';
|
||||
|
||||
export const CNSL_FORM_FIELD = new InjectionToken<CnslFormFieldComponent>('CnslFormFieldComponent');
|
||||
|
||||
@@ -29,6 +29,15 @@ class CnslFormFieldBase {
|
||||
constructor(public _elementRef: ElementRef) {}
|
||||
}
|
||||
|
||||
interface Help {
|
||||
type: 'hints' | 'errors';
|
||||
validationErrors?: Array<ValidationError>;
|
||||
}
|
||||
interface ValidationError {
|
||||
i18nKey: string;
|
||||
params: any;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'cnsl-form-field',
|
||||
templateUrl: './form-field.component.html',
|
||||
@@ -59,19 +68,24 @@ export class CnslFormFieldComponent extends CnslFormFieldBase implements OnDestr
|
||||
@ViewChild('inputContainer') _inputContainerRef!: ElementRef;
|
||||
@ContentChild(MatFormFieldControl) _controlNonStatic!: MatFormFieldControl<any>;
|
||||
@ContentChild(MatFormFieldControl, { static: true }) _controlStatic!: MatFormFieldControl<any>;
|
||||
@Input() public disableValidationErrors = false;
|
||||
|
||||
get _control(): MatFormFieldControl<any> {
|
||||
return this._explicitFormFieldControl || this._controlNonStatic || this._controlStatic;
|
||||
}
|
||||
set _control(value: MatFormFieldControl<any>) {
|
||||
this._explicitFormFieldControl = value;
|
||||
}
|
||||
|
||||
private _explicitFormFieldControl!: MatFormFieldControl<any>;
|
||||
readonly stateChanges: Subject<void> = new Subject<void>();
|
||||
public help$?: Observable<Help>;
|
||||
|
||||
_subscriptAnimationState: string = '';
|
||||
|
||||
@ContentChildren(CNSL_ERROR as any, { descendants: true }) _errorChildren!: QueryList<CnslErrorDirective>;
|
||||
|
||||
// TODO: Remove?
|
||||
@HostListener('blur', ['false'])
|
||||
_focusChanged(isFocused: boolean): void {
|
||||
if (isFocused !== this.focused && !isFocused) {
|
||||
@@ -91,8 +105,6 @@ export class CnslFormFieldComponent extends CnslFormFieldBase implements OnDestr
|
||||
}
|
||||
|
||||
public ngAfterViewInit(): void {
|
||||
// Avoid animations on load.
|
||||
this._subscriptAnimationState = 'enter';
|
||||
this._changeDetectorRef.detectChanges();
|
||||
}
|
||||
|
||||
@@ -103,25 +115,21 @@ export class CnslFormFieldComponent extends CnslFormFieldBase implements OnDestr
|
||||
|
||||
public ngAfterContentInit(): void {
|
||||
this._validateControlChild();
|
||||
this.mapHelp();
|
||||
|
||||
const control = this._control;
|
||||
control.stateChanges.pipe(startWith(null)).subscribe(() => {
|
||||
control.stateChanges.pipe(startWith(null), takeUntil(this._destroyed)).subscribe(() => {
|
||||
this._syncDescribedByIds();
|
||||
this._changeDetectorRef.markForCheck();
|
||||
});
|
||||
|
||||
// Run change detection if the value changes.
|
||||
// TODO: Is that not redundant (see immediately above)?
|
||||
if (control.ngControl && control.ngControl.valueChanges) {
|
||||
control.ngControl.valueChanges
|
||||
.pipe(takeUntil(this._destroyed))
|
||||
.subscribe(() => this._changeDetectorRef.markForCheck());
|
||||
}
|
||||
|
||||
// Update the aria-described by when the number of errors changes.
|
||||
this._errorChildren.changes.pipe(startWith(null)).subscribe(() => {
|
||||
this._syncDescribedByIds();
|
||||
this._changeDetectorRef.markForCheck();
|
||||
});
|
||||
}
|
||||
|
||||
/** Throws an error if the form field's control is missing. */
|
||||
@@ -147,14 +155,68 @@ export class CnslFormFieldComponent extends CnslFormFieldBase implements OnDestr
|
||||
}
|
||||
}
|
||||
|
||||
private mapHelp(): void {
|
||||
const validationErrors$: Observable<Array<ValidationError>> = this.disableValidationErrors
|
||||
? of([])
|
||||
: this._control.stateChanges?.pipe(
|
||||
map(() => this.currentValidationErrors()),
|
||||
startWith([]),
|
||||
) || of([]);
|
||||
|
||||
const childrenErrors$: Observable<boolean> = this._errorChildren.changes.pipe(
|
||||
map(() => {
|
||||
return this._errorChildren.length > 0;
|
||||
}),
|
||||
startWith(false),
|
||||
);
|
||||
|
||||
this.help$ = combineLatest([validationErrors$, childrenErrors$]).pipe(
|
||||
map((combined) => {
|
||||
return combined[0].length >= 1
|
||||
? <Help>{
|
||||
type: 'errors',
|
||||
validationErrors: combined[0],
|
||||
}
|
||||
: combined[1]
|
||||
? <Help>{
|
||||
type: 'errors',
|
||||
}
|
||||
: <Help>{
|
||||
type: 'hints',
|
||||
validationErrors: undefined,
|
||||
};
|
||||
}),
|
||||
);
|
||||
this._changeDetectorRef.markForCheck();
|
||||
}
|
||||
|
||||
private currentValidationErrors(): Array<ValidationError> {
|
||||
return (
|
||||
Object.entries(this._control.ngControl?.control?.errors || [])
|
||||
?.filter(this.filterErrorsProperties)
|
||||
.map(this.mapToValidationError)
|
||||
.filter(this.distinctFilter) || []
|
||||
);
|
||||
}
|
||||
|
||||
private filterErrorsProperties(kv: [string, any]): boolean {
|
||||
return typeof kv[1] == 'object' && (kv[1] as { valid: boolean }).valid === false;
|
||||
}
|
||||
|
||||
private mapToValidationError(kv: [string, any]): ValidationError {
|
||||
return {
|
||||
i18nKey: 'ERRORS.INVALID_FORMAT',
|
||||
...(kv[1] as ValidationError | any),
|
||||
};
|
||||
}
|
||||
|
||||
private distinctFilter(_: ValidationError, index: number, arr: Array<ValidationError>): boolean {
|
||||
return arr.findIndex((item) => item.i18nKey) === index;
|
||||
}
|
||||
|
||||
/** Determines whether a class from the NgControl should be forwarded to the host element. */
|
||||
_shouldForward(prop: keyof NgControl): boolean {
|
||||
const ngControl: any = this._control ? this._control.ngControl : null;
|
||||
return ngControl && ngControl[prop];
|
||||
}
|
||||
|
||||
/** Determines whether to display hints or errors. */
|
||||
_getDisplayedMessages(): 'error' | 'hint' {
|
||||
return this._errorChildren && this._errorChildren.length > 0 ? 'error' : 'hint';
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
<div class="cnsl-form-field-wrapper" (click)="_control.onContainerClick && _control.onContainerClick($event)">
|
||||
<ng-content select="cnsl-label"></ng-content>
|
||||
<div class="cnsl-rel" #inputContainer>
|
||||
<ng-content></ng-content>
|
||||
<ng-content select="cnslSuffix"></ng-content>
|
||||
</div>
|
||||
<div class="cnsl-form-field-subscript-wrapper" [ngSwitch]="_getDisplayedMessages()">
|
||||
<div *ngSwitchCase="'error'" class="cnsl-form-field-error-wrapper" [@transitionMessages]="_subscriptAnimationState">
|
||||
<ng-content select="cnsl-error"></ng-content>
|
||||
</div>
|
||||
<div *ngSwitchCase="'hint'" class="cnsl-form-field-hint-wrapper" [@transitionMessages]="_subscriptAnimationState">
|
||||
<ng-content select="cnsl-hint"></ng-content>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,15 +1,16 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { NgModule } from '@angular/core';
|
||||
import { MatRippleModule } from '@angular/material/core';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { LabelModule } from 'src/app/modules/label/label.module';
|
||||
|
||||
import { LabelComponent } from '../label/label.component';
|
||||
import { CnslErrorDirective } from './error.directive';
|
||||
import { CnslFormFieldComponent } from './form-field.component';
|
||||
import { CnslErrorDirective } from './error/error.directive';
|
||||
import { CnslFormFieldComponent } from './field/form-field.component';
|
||||
|
||||
@NgModule({
|
||||
declarations: [CnslFormFieldComponent, CnslErrorDirective],
|
||||
imports: [CommonModule, MatRippleModule, LabelModule],
|
||||
imports: [CommonModule, MatRippleModule, LabelModule, TranslateModule],
|
||||
exports: [CnslFormFieldComponent, LabelComponent, CnslErrorDirective],
|
||||
})
|
||||
export class FormFieldModule {}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { AbstractControl, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
|
||||
|
||||
export function containsSymbolValidator(c: AbstractControl): ValidationErrors | null {
|
||||
return regexpValidator(c, /[^a-z0-9]/gi, 'ERRORS.SYMBOLERROR');
|
||||
}
|
||||
|
||||
export function containsNumberValidator(c: AbstractControl): ValidationErrors | null {
|
||||
return regexpValidator(c, /[0-9]/g, 'ERRORS.NUMBERERROR');
|
||||
}
|
||||
|
||||
export function containsUpperCaseValidator(c: AbstractControl): ValidationErrors | null {
|
||||
return regexpValidator(c, /[A-Z]/g, 'ERRORS.UPPERCASEMISSING');
|
||||
}
|
||||
|
||||
export function containsLowerCaseValidator(c: AbstractControl): ValidationErrors | null {
|
||||
return regexpValidator(c, /[a-z]/g, 'ERRORS.LOWERCASEMISSING');
|
||||
}
|
||||
|
||||
export function phoneValidator(c: AbstractControl): ValidationErrors | null {
|
||||
return regexpValidator(c, /^($|(\+|00)[0-9 ]+$)/, 'ERRORS.PHONE');
|
||||
}
|
||||
|
||||
export function requiredValidator(c: AbstractControl): ValidationErrors | null {
|
||||
return i18nErr(Validators.required(c), 'ERRORS.REQUIRED');
|
||||
}
|
||||
|
||||
export function emailValidator(c: AbstractControl): ValidationErrors | null {
|
||||
return i18nErr(Validators.email(c), 'ERRORS.NOTANEMAIL');
|
||||
}
|
||||
|
||||
export function minLengthValidator(minLength: number): ValidatorFn {
|
||||
return (c: AbstractControl): ValidationErrors | null => {
|
||||
return i18nErr(Validators.minLength(minLength)(c), 'ERRORS.MINLENGTH', { requiredLength: minLength });
|
||||
};
|
||||
}
|
||||
|
||||
export function passwordConfirmValidator(passwordControlName: string = 'password') {
|
||||
return (c: AbstractControl): ValidationErrors | null => {
|
||||
if (!c.parent || !c) {
|
||||
return null;
|
||||
}
|
||||
const pwd = c.parent.get(passwordControlName);
|
||||
const cpwd = c;
|
||||
|
||||
if (!pwd || !cpwd) {
|
||||
return null;
|
||||
}
|
||||
if (pwd.value !== cpwd.value) {
|
||||
return i18nErr(undefined, 'ERRORS.PWNOTEQUAL');
|
||||
}
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
function regexpValidator(c: AbstractControl, regexp: RegExp, i18nKey: string): ValidationErrors | null {
|
||||
return !c.value || regexp.test(c.value) ? null : i18nErr({ invalid: true }, i18nKey, { regexp: regexp });
|
||||
}
|
||||
|
||||
function i18nErr(err: ValidationErrors | null | undefined, i18nKey: string, params?: any): ValidationErrors | null {
|
||||
if (err === null) {
|
||||
return null;
|
||||
} else {
|
||||
return {
|
||||
...err,
|
||||
invalid: true,
|
||||
[i18nKey.toLowerCase().replaceAll('.', '')]: {
|
||||
valid: false,
|
||||
i18nKey: i18nKey,
|
||||
params: params,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user