-
Notifications
You must be signed in to change notification settings - Fork 426
Expand file tree
/
Copy pathuser-form.component.ts
More file actions
98 lines (87 loc) · 2.78 KB
/
user-form.component.ts
File metadata and controls
98 lines (87 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../core/auth.service';
import { ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.scss']
})
export class UserFormComponent implements OnInit {
userForm: FormGroup;
newUser = true; // to toggle login or signup form
passReset = false; // set to true when password reset is triggered
formErrors = {
'email': '',
'password': ''
};
validationMessages = {
'email': {
'required': 'Email is required.',
'email': 'Email must be a valid email'
},
'password': {
'required': 'Password is required.',
'pattern': 'Password must be include at one letter and one number.',
'minlength': 'Password must be at least 4 characters long.',
'maxlength': 'Password cannot be more than 40 characters long.',
}
};
constructor(private fb: FormBuilder, private auth: AuthService) { }
ngOnInit(): void {
this.buildForm();
}
toggleForm() {
this.newUser = !this.newUser;
}
signup(): void {
this.auth.emailSignUpWithDisplayName(this.userForm.value['email'],
this.userForm.value['password'],
this.userForm.value['displayName'])
}
login(): void {
this.auth.emailLogin(this.userForm.value['email'], this.userForm.value['password'])
}
resetPassword() {
this.auth.resetPassword(this.userForm.value['email'])
.then(() => this.passReset = true)
}
buildForm(): void {
this.userForm = this.fb.group({
'email': ['', [
Validators.required,
Validators.email
]
],
'password': ['', [
Validators.pattern('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$'),
Validators.minLength(6),
Validators.maxLength(25)
]
],
'displayName': ['', [
]]
});
this.userForm.valueChanges.subscribe(data => this.onValueChanged(data));
this.onValueChanged(); // reset validation messages
}
// Updates validation state on form changes.
onValueChanged(data?: any) {
if (!this.userForm) { return; }
const form = this.userForm;
for (const field in this.formErrors) {
if (Object.prototype.hasOwnProperty.call(this.formErrors, field)) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
if (Object.prototype.hasOwnProperty.call(control.errors, key)) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
}
}
}