typescript angular2_validation_service

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript angular2_validation_service相关的知识,希望对你有一定的参考价值。

import {Component, OnInit} from '@angular/core';
import {FormGroup, FormControl, Validators} from "@angular/forms";
import {SsnValidatorService} from "./ssn-validator.service";
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/debounceTime';

function ssnValidator(control: FormControl): {[key: string]: any} {
  const value: string = control.value || '';
  const valid = value.match(/^\d{9}$/);
  return valid ? null : {ssn: true};
}

@Component({
  selector: 'app-root',
  template: `
    <form [formGroup]="myForm">
      <h2>Sync and async validation demo </h2>
      
      Enter your SSN: <input type="text" formControlName="ssnControl">
           <span *ngIf ="myForm.hasError('ssn', 'ssnControl'); else validSSN"> SSN is invalid.</span>
           <ng-template #validSSN> SSN is valid.</ng-template>
      
           <span *ngIf ="myForm.hasError('work', 'ssnControl')"> {{myForm.get('ssnControl').errors.work}}</span>
      
           <span *ngIf ="myForm.hasError('cash')"> {{myForm.errors.cash}}</span> 
    </form>
  `
})
export class AppComponent implements OnInit{

  myForm: FormGroup;

  constructor(private ssnValidatorService: SsnValidatorService) {
    this.myForm = new FormGroup({
      ssnControl: new FormControl('',
                       ssnValidator,
                       ssnValidatorService.checkWorkAuthorization.bind(ssnValidatorService))
    });
  }

  ngOnInit(){
    let ssnControl = this.myForm.get('ssnControl');
    ssnControl.valueChanges
      .debounceTime(2000)
      .filter(val => val.length === 9)
      .switchMap(ssnValue => this.ssnValidatorService.checkWorkAuthorizationV2(ssnValue))
      .subscribe((res) => {
          this.myForm.setErrors(res);
        }
      );
  }
}
import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable";
import 'rxjs/add/observable/of';
import {AbstractControl, ValidationErrors} from "@angular/forms";


@Injectable()
export class SsnValidatorService {

  constructor() { }

  /** This function can be used by form controls in a way prescribed in Angular doc
   */
  checkWorkAuthorization(field: AbstractControl):Observable<ValidationErrors | null>{

    // in the real world you'd make an HTTP call to server to check if the value is valid

    return Observable.of(field.value.indexOf('123') >=0 ? null: {work: " you're not authorized to work"});
  }
  /**
   *
   This function is returns validation in the format prescribed by Angular validation API.,
   But this function  can't be attached to the form control as a validator.
   Invoke it using the switchmap/subscribe combo (see app.component.ts)
   */
  checkWorkAuthorizationV2(ssn: string):Observable<ValidationErrors | null>{

    // in the real world you'd make an HTTP call to server to check if the value is valid

    return Observable.of(ssn.indexOf('123') >=0 ? null: {cash: " - you can only work for cash"});
  }








/*  checkWorkAuthorizationV2(ssn: string):Observable<ValidationErrors | null>{

    // in the real world you'd make an HTTP call to server
    // to check if the value is valid

  return Observable.create(observer => {

        ssn.indexOf('123') >=0 ? observer.next(): observer.next({cash: "you can only work for cash"});
       // observer.complete();

    })

  }*/




}

以上是关于typescript angular2_validation_service的主要内容,如果未能解决你的问题,请参考以下文章

TypeScript入门五:TypeScript的接口

TypeScript系列教程--初探TypeScript

TypeScript入门三:TypeScript函数类型

typescript使用 TypeScript 开发 Vue 组件

认识 TypeScript

Learining TypeScript TypeScript 简介