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();
})
}*/
}