【问题标题】:Reactive form validation from ts来自 ts 的反应式表单验证
【发布时间】:2020-02-17 15:28:30
【问题描述】:

我正在尝试使用类型集中验证消息。 假设表单是原始的或未触及的,即当用户提交表单而不触及我想显示的字段时,我只需要名称并且只需要电子邮件消息

我已经添加了提交的布尔值来计算,但 ngIf 将始终评估为 false

validationCondition(type: string, controlName: string): boolean {
     return this.myForm.get(`${controlName}`).hasError(`${type}`) &&(this.myForm.get(`${controlName}`).touched || this.myForm.get(`${controlName}`).dirty);
  }  

在这里我们可以做点什么,但我不知道我应该放什么才能使用 submit 也

链接:https://stackblitz.com/edit/angular-tiey4d

我希望在用户提交表单而不触及任何字段的情况下看到姓名是必需的,并且电子邮件是必需的。我还想在输入字段或离开字段时看到验证消息。

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以在根 obj 中使用此布尔值检查表单是否有错误。

    this.myForm.invalid
    

    【讨论】:

    • 这样,当您输入验证时,如果我将无效与触摸一起输入,则它会显示所有验证消息。感谢您的回复。
    【解决方案2】:

    就在提交上

     onSubmit() { 
        if (!this.myForm.valid) //if not valid
        {
           this.submitted = true  // because you put the condition "if submitted"
           this.myForm.markAllAsTouched() //mark all the controls as touched
        }else
        {
           console.log(this.myForm.value)
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2020-01-13
      • 2017-12-30
      • 2019-05-04
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 2019-07-28
      相关资源
      最近更新 更多