1

我有一个表单,但我使用表单外的按钮将数据提交到 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);
        });
    }   
}
4

1 回答 1

0

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

于 2019-01-19T05:06:08.640 回答