angular2中的自定义验证程序指令

时间:2016-10-28 09:33:23

标签: angular angularjs-directive

我正在尝试为自定义验证构建一个datepicker指令 我使用ng-bootstrap datepicker。
我有一个问题,我不知道如何使用表单验证。

我的例子:plnkr

指令

  validate(c: AbstractControl): { [key: string]: any } {
        let end;
        let start;
        let v = c.value;
        let e = c.root.get(this.startdate);
        console.log("c",c);
        if( v && e.value ){
           if( this.isStartDate === true ){
              start = this.getDateSting(v);
              end = this.getDateSting(e.value);
           }else{
              end = this.getDateSting(v);
              start = this.getDateSting(e.value);
           }

           if ( start > end ) {
              console.log("start >= end");
              e.setErrors({
                validateDateCompare: false
              })
            }else{
                console.log("end >= start");
                if(e.errors){
                  delete e.errors['validateDateCompare'];
                }
            }
            return null;
        }
    }
}
        <div class="datepicker-section">
                        <div class="input-group">
                            <input class="form-control" name="startdate" [(ngModel)]="searchArea.startdate" ngbDatepicker #start="ngbDatepicker" validateDateCompare="enddate" isStartDate="true">
                            <div class="input-group-addon" (click)="clearDatepicker(start,searchArea)">
                                X
                            </div>
                            <div class="input-group-addon" (click)="start.toggle()">
                                Search
                            </div>
                        </div>
                    </div>
        <small *ngIf="start.errors" class="text-danger">
          must big than enddate
        </small>

0 个答案:

没有答案