角度承诺形式验证

时间:2020-03-08 06:45:52

标签: angular angular-promise angular-forms

我是Angular的新手,正在尝试理解基本的表单验证代码。在这里,下面的checkValidEmail试图检查用户输入的电子邮件是否等于super@seret.com。我不明白的是,当电子邮件为super@seret.com时,为什么表单验证为假? 有关完整的源代码-https://stackblitz.com/edit/angular-p4bz6e?file=src%2Fapp%2Fapp.component.ts

checkValidEmail(control: AbstractControl) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (control.value === 'super@seret.com') {
            resolve({ test: false })
        } else {resolve(null)}
      }, 2000)
    })

2 个答案:

答案 0 :(得分:1)

表单验证将失败,因为在抽象控件或用户定义的验证checkValidEmail中,您将返回{ emailIsTaken: true }。因此自定义验证返回的所有响应都将添加emailcontrol错误属性。

由于从定义的抽象控件中添加的错误,因此表单无效。

尝试如下在app.component.html中进行打印。

<p> Form emailIsTaken {{form.controls.email.errors | json}}</p>

答案 1 :(得分:0)

只需在自定义验证中更改条件,然后尝试逻辑,

checkValidEmail(control: AbstractControl) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (control.value !== 'super@secret.com') {
        resolve({ emailIsTaken: true })
      } else {resolve(null)}
    }, 2000)
  })
相关问题