验证器在角度2

时间:2017-02-06 05:07:21

标签: javascript validation angular

我正在创建一个日期验证器。但我想从两个将被验证的日期字段中传递动态值。

  buildForm(): void {
    this.fileForm = this.fb.group({
      'name': [this.fileComponent.name, [
          Validators.required,
          Validators.minLength(4),
          Validators.maxLength(24),
          forbiddenNameValidator(/bob/i)
        ]
      ],
      'type': [this.fileComponent.type,Validators.required],
      'roles':    [this.fileComponent.roles, Validators.required],
      'toDate':    [this.fileComponent.toDate, Validators.required],
      'fromDate':    [this.fileComponent.fromDate, [Validators.required,forbiddenDateValidator(this.fileComponent.toDate,this.fileComponent.fromDate)]]
    });
  }

在forbiddenDateValidator中我想动态传递给Date和fromDate。 验证码:

import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';

/** A hero's name can't match the given regular expression */
export function forbiddenDateValidator(fromDate: string,toDate: string): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    console.log("from date "+fromDate+"        todate   "+toDate);
    let val:boolean=false;
    if (toDate<fromDate) {
      val=true;
    }
    const date1 = control.value;
    return val ? {'forbiddenDate': {date1} } : null;
  };
}

@Directive({
  selector: '[forbiddenDate]',
  providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
})
export class ForbiddenValidatorDirective implements Validator{
  @Input() fromDate: string;
  @Input() toDate: string;
  private valFn = Validators.nullValidator;

 /* ngOnChanges(changes: SimpleChanges): void {
    const change = changes['fromDate'];
    const change1 = changes['toDate'];
    if (change1<change) {
      this.valFn = forbiddenDateValidator(true);
    } else {
      this.valFn = Validators.nullValidator;
    }
  }*/

  validate(control: AbstractControl): {[key: string]: any} {
    return this.valFn(control);
  }
}

它不起作用,fromdate和todate的值没有反映在forbiddenDateValidator中。 请建议我如何实现这个和ngOnChanges功能。

0 个答案:

没有答案