1 | import { Component, OnInit } from '@angular/core';
|
---|
2 | import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
|
---|
3 | import { DynamicDialogRef } from 'primeng/dynamicdialog';
|
---|
4 | import { CustomValidators } from 'src/app/providers/CustomValidators';
|
---|
5 | import { UserDto } from 'src/app/_models/dto/userDto';
|
---|
6 | import { UserService } from 'src/app/_services/user.service';
|
---|
7 |
|
---|
8 | @Component({
|
---|
9 | selector: 'app-register',
|
---|
10 | templateUrl: './register.component.html',
|
---|
11 | styleUrls: ['./register.component.css']
|
---|
12 | })
|
---|
13 | export class RegisterComponent implements OnInit {
|
---|
14 |
|
---|
15 | user: UserDto;
|
---|
16 | form: FormGroup;
|
---|
17 | usernames: string[];
|
---|
18 |
|
---|
19 |
|
---|
20 | constructor(private ref: DynamicDialogRef,
|
---|
21 | formBuilder: FormBuilder, private userService: UserService) {
|
---|
22 | this.user = new UserDto();
|
---|
23 | this.usernames = [];
|
---|
24 |
|
---|
25 | this.form = formBuilder.group({
|
---|
26 | fullName: new FormControl('', [Validators.required, Validators.minLength(3)]),
|
---|
27 | username: new FormControl('', [Validators.required, Validators.email]),
|
---|
28 | password: new FormControl('', [Validators.required, Validators.minLength(6)]),
|
---|
29 | confirmPassword: new FormControl('', [Validators.required, Validators.minLength(6)])
|
---|
30 | }, {
|
---|
31 | validators: [
|
---|
32 | CustomValidators.mustMatch('password', 'confirmPassword'),
|
---|
33 | this.validateUsername('username')
|
---|
34 | ]
|
---|
35 | });
|
---|
36 | }
|
---|
37 |
|
---|
38 | ngOnInit(): void {
|
---|
39 | }
|
---|
40 |
|
---|
41 | onFormSubmitSignUp(user) {
|
---|
42 | const { valid } = this.form;
|
---|
43 | if (valid) {
|
---|
44 | this.ref.close(user);
|
---|
45 | }
|
---|
46 | }
|
---|
47 |
|
---|
48 | validateUsername(username: string) {
|
---|
49 | return (formGroup: FormGroup) => {
|
---|
50 | const control = formGroup.controls[username];
|
---|
51 |
|
---|
52 | if (control.errors && !control.errors.validateUsername) {
|
---|
53 | return;
|
---|
54 | }
|
---|
55 |
|
---|
56 | this.userService.getAllUsernames().subscribe(
|
---|
57 | data => {
|
---|
58 | this.usernames = data;
|
---|
59 | for (let i = 0; i < this.usernames.length; i++) {
|
---|
60 | if (control.value === this.usernames[i]) {
|
---|
61 | control.setErrors({ validateUsername: true });
|
---|
62 | break;
|
---|
63 | } else {
|
---|
64 | control.setErrors(null);
|
---|
65 | }
|
---|
66 | }
|
---|
67 | }
|
---|
68 | );
|
---|
69 | return null;
|
---|
70 | };
|
---|
71 |
|
---|
72 | }
|
---|
73 |
|
---|
74 | }
|
---|