Angular Custom Form Validator (async)

JS
S
JavaScript

Angular 8 Custom Form Validator

1import { AbstractControl, ValidationErrors } from '@angular/forms';
2import { Observable, Subject, BehaviorSubject, ReplaySubject, of } from 'rxjs';
3import { of as observableOf } from 'rxjs';
4
5export function mpanValidator(control: AbstractControl): Observable<ValidationErrors | null> {
6  const { value } = control;
7  const primes = [3, 5, 7, 13, 17, 19, 23, 29, 31, 37, 41, 43];
8  let sum = 0;
9  const mpanSplittedStr = value.toString().split('');
10  const mpanSplitted = mpanSplittedStr.map(Number);
11
12  if ((mpanSplitted.length - 1) === primes.length) {
13    for (let index = 0; index < primes.length; index++) {
14      sum += mpanSplitted[index] * primes[index];
15    }
16    const testResult: boolean = ((sum % 11 % 10) === mpanSplitted[mpanSplitted.length - 1]);
17    if (testResult){
18      return observableOf(null);
19    }
20    return observableOf({ 'validMpan': false });
21  } else {
22    return observableOf({ 'validMpan': false });
23  }
24}
25

Created on 7/31/2019