【问题标题】:custom validation acces form components自定义验证访问表单组件
【发布时间】:2018-04-24 07:37:15
【问题描述】:

我想对 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
    }

【问题讨论】:

  • 是的,可以,你能更新你的模块文件吗

标签: angular custom-validators


【解决方案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

【讨论】:

  • 您有示例如何使用表单模板执行此操作。那么要在 html 控件 中放置一个验证器,并且在 typescript 中不使用 formbuilder?
【解决方案2】:

你可以喜欢

@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
    }

也可以参考这个链接:custom validatorcustom validtor with reverse match

【讨论】:

  • 我想在这里访问另一个控件。如果我这样做 c.root.get('control') 它也是 null
  • 查看以上链接
  • 嗨罗伯特,谢谢你的回复,前提是我执行代码 let e = c.root.get(this.validateEqual);这导致空
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多