如何使用angular2设置Validator不接受索引0的选定选项

时间:2017-01-18 03:56:06

标签: angular typescript

我使用像这样的选择

<div class="form-group row" [ngClass]="{'has-error': (!form.controls['blockFirstIndex'].valid && form.controls['blockFirstIndex'].touched), 'has-success': (form.controls['blockFirstIndex'].valid && form.controls['blockFirstIndex'].touched)}">
      <label class="col-sm-3 control-label">blockFirstIndex</label>
      <div class="col-sm-9">
            <select formControlName="blockFirstIndex" [(ngModel)]="value" class="form-control">
                 <option *ngFor="let item of items" [disabled]="item.id==0" [ngValue]="item">{{item.name}}</option>
            </select>
      </div>
</div>

我的验证员

this.form = this.fb.group({
    'blockFirstIndex': ['', Validators.compose([Validators.required])],
});

如何使验证器不接受索引0的选择选项?

1 个答案:

答案 0 :(得分:0)

Form controller could be like this:

blockFirstIndex: new FormControl("", [
                    SelectionValidator.isValidSelection,
                    Validators.required
                ])

and you can define vlaidator like this:

import {FormControl} from '@angular/forms'; 
    export class SelectionValidator {
       static  isValidSelection(control: FormControl){
            if (control.value === "" || control.value=== "0") {
                return { "Please provide a valid selection": true };
            }
            return null;
        }

    }