如何通过单击按钮将验证添加到Datepicker输入中

时间:2019-04-03 15:59:14

标签: angular

我刚刚开始学习Angular 6,并陷入一个涉及将验证消息应用于空的datepicker输入的问题。我希望如果用户单击“提交”按钮并且忘记选择日期,则会显示一条验证消息,显示“请输入日期”。再次,我对此很陌生,感谢您的反馈-到目前为止,我已经粘贴了代码。谢谢!

  <!-- Datepicker code-->
        <div class="row">
            <div class="col-xl-9 col-lg-8">
                <ng-container *ngIf="isLoggedIn()">
                    <form class="form-horizontal" method="get">
                        <fieldset>
                            <div class="form-group row mb">
                                <label class="col-md-3 col-form-label">Date Range</label>
                                <div class="col-md-9">

                                    <!-- The code below is for a date range (picks two dates) -->
                                    <input type="text" class="form-control hasDatepicker" name='dateSelected' id="dateSelected" value=""  data-validation="dateSelected" data-validation-format="mm/dd/yyyy" #drp="bsDaterangepicker" bsDaterangepicker
                                        [bsConfig]="bsConfig" (bsValueChange)="onChangeDates($event)" required>

                                        <ng-container *ngIf=".invalid && (dateSelected.dirty || dateSelected.touched)"
                                        class="alert alert-danger">
                                            <div *ngIf="dateSelected.errors.required">
                                                Name is required.
                                            </div>
                                        </ng-container>

                                    </div>
                            </div>
                        </fieldset>
                    </form>
                    <button type="button" class="btn btn-success" (click)="searchForResults()">Submit</button>
                </ng-container>
            </div>
        </div>

2 个答案:

答案 0 :(得分:0)

您是否尝试过使用响应式表单而不是模板表单方法来执行此操作。 响应式表单使您可以在实现表单组和表单控件时添加所需的逻辑。

答案 1 :(得分:0)

我在下面尝试过,使用ngSubmit并在表单内移动按钮

<form class="form-horizontal" #anyForm="ngForm" name="formExample" (ngSubmit)="searchForResults()">
                    <fieldset>
                        <div class="form-group row mb">
                            <label class="col-md-3 col-form-label">Date Range</label>
                                    <div class="col-md-9">

                                        <!-- The code below is for a date range (picks two dates) -->
                                        <input required class="form-control" type="text"  name='dateSelected' id="dateSelected" [(ngModel)]="model.dateSelected" #dateSelected="ngModel" />

  <div [hidden]="dateSelected.valid || dateSelected.pristine"class="alert alert-danger">
      Date is required
</div>
   </div>
    </div>
    </fieldset>
<button type="submit" class="btn btn-success" >Submit</button>
                        </form>