typescript 角度材料日期选择器最小和最大日期验证消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54828459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular material date-picker min and max date validation messages
提问by Karthik Arwin
How to show the validation messages for min and max dates validation errors in Angular Material Datepicker
如何在Angular Material Datepicker 中显示最小和最大日期验证错误的验证消息
<input [min]="minDate" [max]="maxDate" matInput [matDatepicker]="picker" [formControlName]="date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error class="error-message" *ngIf="formgroup.get('date').hasError('required') && (formgroup.get('date').dirty || formgroup.get('date').touched)">Date is Required</mat-error>
Here Requiredvalidation has been set.
这里设置了必需的验证。
Like same I want to show Date should be higher than 01/01/2019message if user typed the date which is less than minDate.
同样,如果用户输入的日期小于 minDate,我想显示Date 应该高于 01/01/2019消息。
I knew that all the previous dates would be disabled if we set minDate. But in this application, we allow user to type the date too! So when user enters the date which is previous than the minDatedefined, I want to show the error message!
我知道如果我们设置 minDate,所有以前的日期都会被禁用。但是在这个应用程序中,我们也允许用户输入日期!因此,当用户输入的日期早于定义的minDate 时,我想显示错误消息!
Any way to achieve it?
有什么方法可以实现吗?
回答by
You can use the reference to the ngModel to know if the date is in error.
您可以使用对 ngModel 的引用来了解日期是否有误。
In this stackblitz, I have made it so that you can see the errors applied to the input (so that you can know the error), and also displayed the error when the input is in error.
在这个 stackblitz 中,我这样做是为了让您可以看到应用于输入的错误(以便您知道错误),并在输入错误时显示错误。
<mat-form-field class="example-full-width">
<input matInput #input="ngModel" [(ngModel)]="date" [min]="minDate" [max]="maxDate" [matDatepicker]="picker" placeholder="Choose a date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error *ngIf="input.hasError('matDatepickerMax')">Date should be inferior</mat-error>
</mat-form-field>
<br><br><br>
{{ input.errors | json }}