import { Observable } from 'rxjs'; import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; @Component({ selector: 'cm-form-doc-8', templateUrl: './form-doc-8.component.html', styleUrls: ['./form-doc-8.component.css'], providers: [ FormBuilder] }) export class FormDoc8Component implements OnInit { validateForm: FormGroup; submitForm = ($event:any, value:any) => { $event.preventDefault(); for (const key in this.validateForm.controls) { this.validateForm.controls[ key ].markAsDirty(); } console.log(value); }; resetForm($event: MouseEvent) { $event.preventDefault(); this.validateForm.reset(); for (const key in this.validateForm.controls) { this.validateForm.controls[ key ].markAsPristine(); } } validateConfirmPassword() { setTimeout(() => { this.validateForm.controls[ 'passwordConfirmation' ].updateValueAndValidity(); }) } userNameAsyncValidator = (control: FormControl): any => { return Observable.create(function (observer:any) { setTimeout(() => { if (control.value === 'JasonWood') { observer.next({ error: true, duplicated: true }); } else { observer.next(null); } observer.complete(); }, 1000); }); }; getFormControl(name:any) { return this.validateForm.controls[ name ]; } emailValidator = (control: FormControl): { [s: string]: boolean } => { const EMAIL_REGEXP = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i; if (!control.value) { return { required: true } } else if (!EMAIL_REGEXP.test(control.value)) { return { error: true, email: true }; } }; passwordConfirmationValidator = (control: FormControl): { [s: string]: boolean } => { if (!control.value) { return { required: true }; } else if (control.value !== this.validateForm.controls[ 'password' ].value) { return { confirm: true, error: true }; } }; birthDayValidator = (control: FormControl): any => { if (new Date(control.value) > new Date()) { return { expired: true, error: true } } }; constructor(private fb: FormBuilder) { this.validateForm = this.fb.group({ userName : [ '', [ Validators.required ], [ this.userNameAsyncValidator ] ], email : [ '', [ this.emailValidator ] ], birthDay : [ '', [ this.birthDayValidator ] ], password : [ '', [ Validators.required ] ], passwordConfirmation: [ '', [ this.passwordConfirmationValidator ] ], comment : [ '', [ Validators.required ] ] }); } ngOnInit() { } }