我想为angular2进行自定义验证。此验证必须访问表单的另一个组件。这可能吗?
我的模板
<input type="tekst" id="startDate" name="startDate" [(ngModel)]="model.startDate" #startDate="ngModel" >
<input type="tekst" id="endDate" name="endDate" [(ngModel)]="model.endDate" #endDate="ngModel" customValidator>
我的验证员
...
@Directive({
selector: '[customValidator][ngModel][customValidator][formControl]',
providers: [
provide : NG_VALIDATORS,
useExisting : forwardRef(() = > CustomValidator),
Multi : true
}]
})
export class CustomValidator impelments Validator {
constructor(){}
validate(c : FormControl) : {[key : string] : any} {
// HOW TO ACCESS startDate CONTROL HERE? OR ITS VALUE? OR THE MODEL
}
答案 0 :(得分:1)
如果要实现交叉验证,则应将验证移至祖先控件。
然后您的验证方法如下所示:
validate(fg: FormGroup) {
const start = fg.get('startDate').value;
const end = fg.get('enDate').value;
return start !== null && end !== null && start < end
? null
: { range: true };
};
详细了解交叉验证here。
答案 1 :(得分:0)
你可以喜欢
@Directive({
selector: '[customValidator][ngModel][customValidator][formControl]',
providers: [
provide : NG_VALIDATORS,
useExisting : forwardRef(() = > CustomValidator),
Multi : true
}]
})
export class CustomValidator impelments Validator {
constructor(){}
validate(c : FormControl) : {[key : string] : any} {
let control_value= c.value;
// HOW TO ACCESS startDate CONTROL HERE? OR ITS VALUE? OR THE MODEL
}