我正在尝试使用反应形式验证日期格式 如果格式不匹配则显示错误信息 (MM/DD/YYYY)
有效的日期格式是 2020 年 6 月 30 日(月/日/年) 12/30/2020(月/日/年)
这是我所做的
组件
initForm() {
this.filterForm = this.formBuilder.group({
valueDate: [this.transactionFilter.valueDate,Validators.pattern(/^(0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/[0-9]{4}$/)]
}, { validators: this.validateFormControls });
}
validateFormControls(control: AbstractController){
//some other validations here
}
模板
<form [formGroup]="filterForm" (ngSubmit)="onSubmit()" >
<div class="col">
<mat-form-field>
<mat-label>Value Date</mat-label>
<input matInput [matDatepicker]="txtValueDate" placeholder="MM/DD/YYYY" formControlName="valueDate">
<mat-datepicker-toggle matSuffix [for]="txtValueDate"></mat-datepicker-toggle>
<mat-datepicker #txtValueDate></mat-datepicker>
<!-- <mat-error *ngIf="filterForm.controls['valueDate'].hasError()">Invalid date Format</mat-error> -->
</mat-form-field>
</div>
<button mat-raised-button color="primary" type="submit" [disabled]="!filterForm.valid">submit</button>
</form >
当我输入日期(手动/日期选择器)时,提交按钮总是被禁用。 有没有更好的方法来以反应形式进行日期验证?
默认的日期选择器格式是 yyyy-MM-dd 所以你应该这样做:
组件
export class DateickerComponent {
public dateForm: FormGroup;
constructor() {
var today: string | null = new DatePipe("en-US").transform(new Date(), "yyyy-MM-dd");
this.dateForm = new FormGroup({
date: new FormControl(today, Validators.required)
});
}
}
模板:
<form [formGroup]="dateForm" novalidate>
<input type="date" formControlName="date">
<form>
您拥有的正则表达式匹配 DD/MM/YYYY 日期模式,用于澳大利亚和英国等地。
对于您所说的 MM/DD/YYYY 的美国格式,您需要交换前两组才能实现
(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])\/[0-9]{4}
这足以验证格式。然而,它不会捕捉到像 2 月 30 日这样的事情。 对于这些类型的验证,我建议使用自定义验证器。我在下面粘贴了一个粗略的。它仍然 不处理二月和闰年,实际上限制了年份,但会让你大部分时间。
import {FormControl} from '@angular/forms';
export function dateValidator(control: FormControl) {
if (!control.value) {
return { 'datecheck' : true };
}
let curval:string = control.value;
let pieces: string[] = curval.split("/");
if (!pieces || pieces.length != 3) {
return { 'datecheck' : true };
}
let month:number = +pieces[1];
if (month > 12 || month < 1) {
return { 'datecheck' : true };
}
let day:number = +pieces[0];
if (day < 1) {
return { 'datecheck' : true };
}
switch (month) {
case 9:
case 4:
case 6:
case 11:
if (day > 30) {
return { 'datecheck' : true };
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 9:
case 10:
case 12:
if (day > 31) {
return { 'datecheck' : true };
}
break;
case 2:
if (day > 29) {
return { 'datecheck' : true };
}
break;
}
let year:number = +pieces[2];
if (year > 2100 || year < 1970) {
return { 'datecheck' : true };
}
let curdate : Date = new Date(+pieces[2], month, day);
if (!isNaN(curdate.getTime())) { // this is supposed to tell if curdate is valid
return null;
}
return { 'datecheck' : true };
}