【问题标题】:Angular: Check if a form is valid from outside the form (and show the error messages)Angular:从表单外部检查表单是否有效(并显示错误消息)
【发布时间】:2019-06-13 05:43:42
【问题描述】:

我有一个表单,但我使用表单外的按钮将数据提交到 API。 表单包含必填字段的错误消息,然后显示用户选择输入但不填写任何数据(默认 HTML5 验证)。

由于我实际上并没有提交表单,有没有办法在用户单击表单外的按钮时显示相同的验证消息?

更新:添加了一些代码来进一步解释问题。另外,我忘了提到我正在使用Material Design for Bootstrap 作为我的 CSS 框架。

表单 HTML(component.html):

<form class="custom-form p-2">
    <div class="row">
      <div class="col-sm-6">
        <div class="md-form form-sm">
          <input mdbInputDirective type="text" id="title" [(ngModel)]="dataService.catalog.title" name="title"
            value="{{ dataService.catalog.title }}" required [validateSuccess]="false" placeholder=""
            data-error="This field is mandatory" class="form-control">
          <label for="title">Title</label>
        </div>
      </div>
      <div class="col-sm-2">
        <div class="md-form form-sm">
          <input mdbInputDirective type="date" id="date" [ngModel]="dataService.catalog.date | date:'yyyy-MM-dd'"
            name="date" (ngModelChange)="date = $event" required [validateSuccess]="false"
            placeholder="" data-error="This field is mandatory" class="form-control">
          <label for="date">Date</label>
        </div>
      </div>
      <div class="col-sm-12">
        <div class="md-form form-sm">
          <textarea type="text" id="description" [(ngModel)]="dataService.catalog.description" name="description"
            value="{{ dataService.catalog.description }}" required [validateSuccess]="false" placeholder=""
            data-error="This field is mandatory" class="md-textarea form-control" mdbInputDirective rows="3"></textarea>
          <label for="description">Description</label>
        </div>
      </div>
    </div>
</form>

按钮 HTML (component.html):

<button mdbBtn type="button" color="success" class="waves-light" size="sm" mdbWavesEffect (click)="create()">
    <i class="fa fa-plus-square mr-sm-2 mr-1"></i> Create Catalog
</button>

创建方法(component.ts):

create() {
    //TODO: call the form's own validation method to show the erros?!   

    if(formValid) {
        this.dataService.create(this.dataService.catalog).subscribe(value => {
            console.log(value);
        }, error => {
            console.log(error);
        });
    }   
}

【问题讨论】:

  • 您可以向我们展示您尝试过的东西以便我们提供帮助吗?
  • 用一些代码示例更新了我的问题。这个想法是调用表单自己的验证方法,而不是创建自定义验证机制。

标签: angular validation angular6 angular7 mdbootstrap


【解决方案1】:

您可以使用自己的功能。就像存储每个文本框的值并单击提交按钮验证您的值一样。

【讨论】:

  • 嗨!是的,我知道。但是我想知道是否有更简单的方法,只需调用表单自己的验证方法来显示错误而不创建不同的验证机制。
  • 然后你可以像这样使用 1).ngSubmit.emit() 2)使用 .form.valid
    ...
  • 我已经绑定了,但它不起作用,因为我没有使用有效的 ngForm。
猜你喜欢
  • 1970-01-01
  • 2016-03-05
  • 2017-04-26
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
  • 2021-02-05
  • 2020-04-16
  • 2018-07-22
相关资源
最近更新 更多