响应式/模型驱动的表单 - 自定义验证响应式表单

优质
小牛编辑
116浏览
2023-12-01

让我们假设使用相同的登录表单,但现在我们还要测试我们的密码在其中某处有感叹号。

app/login-form.component.ts

一个简单的函数接受实例,并返回null如果一切都很好。 如果测试失败,它返回一个具有任意命名属性的对象。 属性名称将用于.hasError()测试。

app/login-form.component.ts

  1. <!-- ... -->
  2. <div [hidden]="!password.hasError('needsExclamation')">
  3. Your password must have an exclamation mark!
  4. </div>
  5. <!-- ... -->

有一个自定义验证器来检查感叹号可能是有帮助的,但如果你需要检查一些其他形式的标点符号怎么办? 你可能需要一遍又一遍地写做相同的事情。

考虑前面的例子Validators.minLength(5)。 如果验证器只是一个函数,它们如何允许一个参数来控制长度? 简单,真的。 这不是Angular或TypeScript的一个戏法,它是简单的JavaScript闭包。

假设你有一个函数,它接受一个“最小”参数并返回另一个函数。 从内部定义和返回的函数成为验证器。 闭包引用允许您记住最终调用验证器时的最小值。

让我们将这种思路应用到PunctuationValidator

  1. function hasPunctuation(punctuation: string, errorType: string) {
  2. return function(input: FormControl) {
  3. return input.value.indexOf(punctuation) >= 0 ?
  4. null :
  5. };
  6. }
  7. // ...
  8. this.password = new FormControl('', [
  9. Validators.required,
  10. hasPunctuation('&', 'ampersandRequired')
  11. ]);

app/login-form.component.html

View Example

使用其他输入验证输入

记住前面提到的:输入可以通过.root访问他们的父上下文。 因此,复杂的验证可以通过.root在表单上获取。

  1. function duplicatePassword(input: FormControl) {
  2. }
  3. const exactMatch = input.root.controls.password === input.value;
  4. return exactMatch ? null : { mismatchedPassword: true };
  5. }
  6. // ...
  7. this.duplicatePassword = new FormControl('', [
  8. Validators.required,
  9. duplicatePassword
  10. ]);

View Example