【问题标题】:angular 2 refactor custom validation logic in serviceangular 2 重构服务中的自定义验证逻辑
【发布时间】:2016-12-24 20:06:47
【问题描述】:

我有一个带有多个自定义验证器(仅以下一个)的密码 FormControl:

password = new FormControl('',
    [Validators.required, Validators.minLength(8),
    this.passwordHasLowerCaseValidator.bind(this)]);

passwordHasLowerCaseValidator(control: FormControl) {
    return (...);
}

我想从服务中调用自定义验证器,以便重构我的注册组件,例如

constructor(private customValidators:CustomValidators){}

password = new FormControl('',
    [Validators.required, Validators.minLength(8),
    this.customValidators.passwordHasLowerCaseValidator.bind(this)]);

我已经尝试过了,但它抛出了错误,我猜表单要么无法访问它们,要么无法将数据传递给它..

谢谢!

【问题讨论】:

  • 请发布更多代码。你的服务是@Injectable() 吗?
  • “抛出错误”几乎是有帮助的。请发布确切的错误消息。

标签: validation angular angular2-forms angular2-services


【解决方案1】:

如果您更改验证器以返回类似的验证器函数

passwordHasLowerCaseValidator(customValidators: CustomValidators) {
  return (control: FormControl) => {
    return (...);
    // here you can access "customValidators"
  }
}

并像使用它

constructor(private customValidators:CustomValidators){}

password = new FormControl('',
    [Validators.required, Validators.minLength(8),
    this.customValidators.passwordHasLowerCaseValidator(customValidators).bind(this)]);

你应该得到想要的行为。

【讨论】:

  • 感谢 Günther,您的代码运行良好,只有 passwordHasLowerCaseValidator(customValidators: FormControl){...} 调用是 this.customValidators.passwordHasLowerCaseValidator(this.password).bind(this)
  • 我不这么认为。该函数的调用类似于this.customValidators.passwordHasLowerCaseValidator(customValidators),其中customValidators 的类型为CustomValidators。实际作为验证器传递的返回函数具有验证器所需的参数control: FormControl。我可能从你的问题中误解了一些东西,但如果它按预期工作,我认为我的假设是正确的;-)
  • CustomValidators 位于何处?我应该指出,我使用的是 RC4(ionic 2 beta11 中的当前 Angular 版本),但我之前评论中的代码工作正常……不确定它是否可以测试……
  • 我不明白你的意思。 CustomValidators 作为依赖项传递给您在问题中添加的构造函数。我不知道更多。
猜你喜欢
  • 1970-01-01
  • 2018-03-08
  • 2018-01-26
  • 1970-01-01
  • 2017-12-30
  • 2018-02-03
  • 2019-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多