import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { userForm: FormGroup; userTypes: string[]; constructor(private fb: FormBuilder) { } ngOnInit() { this.userTypes = ['', '']; this.initForm(); } private initForm(): void { this.userForm = this.fb.group({ type: null, name: null, address: null, password: null }); } }
<form class="user-form" [formGroup]="userForm"> <div class="form-group"> <label for="type"> :</label> <select id="type" formControlName="type"> <option disabled value="null"></option> <option *ngFor="let userType of userTypes">{{userType}}</option> </select> </div> <div class="form-group"> <label for="name"> :</label> <input type="text" id="name" formControlName="name" /> </div> <div class="form-group"> <label for="address"> :</label> <input type="text" id="address" formControlName="address" /> </div> <div class="form-group"> <label for="password"> :</label> <input type="text" id="password" formControlName="password" /> </div> </form> <hr/> <div>{{userForm.value|json}}</div>
private initForm(): void { this.userForm = this.fb.group({ type: [null, [Validators.required]], name: [null, [ Validators.required, Validators.pattern(/^[A-z0-9]*$/), Validators.minLength(3)] ], address: null, password: [null, [Validators.required]] }); }
private userTypeSubscription: Subscription;
private subscribeToUserType(): void { this.userTypeSubscription = this.userForm.get('type') .valueChanges .subscribe(value => console.log(value)); }
ngOnInit() { this.userTypes = ['', '']; this.initForm(); this.subscribeToUserType(); }
ngOnDestroy() { this.userTypeSubscription.unsubscribe(); }
private toggleAddressValidators(userType): void { /** */ const address = this.userForm.get('address'); /** */ const addressValidators: ValidatorFn[] = [ Validators.required, Validators.min(3) ]; /** , */ if (userType !== this.userTypes[0]) { address.setValidators(addressValidators); } else { address.clearValidators(); } /** */ address.updateValueAndValidity(); }
private subscribeToUserType(): void { this.userTypeSubscription = this.userForm.get('type') .valueChanges .subscribe(value => this.toggleAddressValidators(value)); }
/** */ private passwordValidator(control: FormControl): ValidationErrors { const value = control.value; /** */ const hasNumber = /[0-9]/.test(value); /** */ const hasCapitalLetter = /[AZ]/.test(value); /** */ const hasLowercaseLetter = /[az]/.test(value); /** */ const isLengthValid = value ? value.length > 7 : false; /** */ const passwordValid = hasNumber && hasCapitalLetter && hasLowercaseLetter && isLengthValid; if (!passwordValid) { return { invalidPassword: ' ' }; } return null; }
private initForm(): void { this.userForm = this.fb.group({ type: [null, [Validators.required]], name: [null, [ Validators.required, Validators.pattern(/^[A-z0-9]*$/), Validators.minLength(3)] ], address: null, password: [null, [ Validators.required, /** */ this.passwordValidator] ] }); }
<div class="form-group"> <label for="password"> :</label> <input type="text" id="password" formControlName="password" /> </div> <div class="error" *ngIf="userForm.get('password').getError('invalidPassword') && userForm.get('password').touched"> {{userForm.get('password').getError('invalidPassword')}} </div>
import { Injectable } from '@angular/core'; import { ValidationErrors } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; @Injectable() export class UserValidationService { private users: string[]; constructor() { /** , */ this.users = ['john', 'ivan', 'anna']; } /** */ validateName(userName: string): Observable<ValidationErrors> { /** */ return new Observable<ValidationErrors>(observer => { const user = this.users.find(user => user === userName); /** , */ if (user) { observer.next({ nameError: ' ' }); observer.complete(); } /** , */ observer.next(null); observer.complete(); }).delay(1000); } }
/** */ nameAsyncValidator(control: FormControl): Observable<ValidationErrors> { return this.userValidation.validateName(control.value); }
/** */ private initForm(): void { this.userForm = this.fb.group({ type: [null, [Validators.required]], name: [null, [ Validators.required, Validators.pattern(/^[A-z0-9]*$/), Validators.minLength(3)], /** */ [this.nameAsyncValidator.bind(this)] ], address: null, password: [null, [ Validators.required, this.passwordValidator] ] }); }
input.ng-pending{ border: 1px solid yellow; }
Source: https://habr.com/ru/post/347126/