Async validator for projects

This commit is contained in:
piotrpekala7 2020-02-17 15:02:25 +01:00
parent e11281ddf6
commit f7143b4d93
3 changed files with 23 additions and 5 deletions

View File

@ -12,9 +12,12 @@
<mat-error *ngIf="form.projectName?.touched && form.projectName?.errors && form.projectName?.errors.required"
>Project name is required</mat-error
>
<mat-error *ngIf="form.projectName?.touched && form.projectName?.errors && form.projectName?.errors.invalidName"
<mat-error *ngIf="form.projectName?.errors && form.projectName?.errors.invalidName"
>Project name is incorrect</mat-error
>
<mat-error *ngIf="form.projectName?.errors && form.projectName?.errors.projectExist"
>Project with this name exists</mat-error
>
</mat-form-field>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()" color="accent">Cancel</button>

View File

@ -9,6 +9,7 @@ import { v4 as uuid } from 'uuid';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { ProjectNameValidator } from '../models/projectNameValidator';
import { ToasterService } from '../../../services/toaster.service';
import { projectNameAsyncValidator } from '../../../validators/project-name-async-validator';
@Component({
@ -31,14 +32,14 @@ export class AddBlankProjectDialogComponent implements OnInit {
private toasterService: ToasterService,
private formBuilder: FormBuilder,
private projectNameValidator: ProjectNameValidator
) {
) {}
ngOnInit() {
this.projectNameForm = this.formBuilder.group({
projectName: new FormControl(null, [Validators.required, projectNameValidator.get])
projectName: new FormControl(null, [Validators.required, this.projectNameValidator.get], [projectNameAsyncValidator(this.server, this.projectService)])
});
}
ngOnInit() {}
get form() {
return this.projectNameForm.controls;
}

View File

@ -0,0 +1,14 @@
import { ProjectService } from '../services/project.service';
import { FormControl } from '@angular/forms';
import { timer } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Server } from '../models/server';
export const projectNameAsyncValidator = (server: Server, projectService: ProjectService) => {
return (control: FormControl) => {
return timer(500).pipe(
switchMap(() => projectService.list(server)),
map(response => (response.find(n => n.name === control.value) ? {projectExist: true} : null))
);
}
}