Angular 当日期格式不正确时,如何验证日期并显示错误
我有个约会(和momentjs)。日期必须为DD/MM/YYYY格式 我的hmtl代码是:Angular 当日期格式不正确时,如何验证日期并显示错误,angular,angular-material,momentjs,angular-reactive-forms,angular-moment,Angular,Angular Material,Momentjs,Angular Reactive Forms,Angular Moment,我有个约会(和momentjs)。日期必须为DD/MM/YYYY格式 我的hmtl代码是: <mat-form-field> <input id="datanint" formControlName="dateBirth" matInput [matDatepicker]="picker" /> <mat-datepicker-toggle matSuffix
<mat-form-field>
<input id="datanint" formControlName="dateBirth" matInput [matDatepicker]="picker" />
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker startView="multi-year" [startAt]="startDate"></mat-datepicker>
</mat-form-field>
这是我的验证器:
export class DateValidator implements Validators {
static validateDate(fdValue: AbstractControl) {
regexDate="...:";
console.log(fdValue);
if(fdValue != null && fdValue.value!= null && fdValue.value.match(regexDate) {
return { pattern: true };
}
}
问题是,当我输入这样的日期(2000年13月13日)时,我希望在我的错误(在表单控件中)中存在模式错误
,但不是这样,因为
fdValue.value
等于null(当输入值为13/13/2000时)。我需要输入值中的fdValue.value
(或我可以用来获取正确值的东西)必须相同,并且日期格式不正确。在此场景中,您无法获取fromControl的值,并且它将始终为console.log(fdValue.value)显示空值代码>可能是因为您在datepicker输入中传递了一些无效的输入。
因此,当您将无效值放入日期选择器时,fdValue
为空,但您仍然可以在error
对象中获取输入
static validateDate(fdValue: AbstractControl) {
const date = fdValue.value;
console.log('date: ',fdValue);
console.log('error: ',fdValue.errors?.matDatepickerParse?.text);
if (date ===null || date==='') return { requiredFromDate: true };
}
但当您输入无效的日期时,您将得到fdValue。value
为null
errors对象包含该输入值
检查代码请检查
static validateDate(fdValue: AbstractControl) {
const date = fdValue.value;
console.log('date: ',fdValue);
console.log('error: ',fdValue.errors?.matDatepickerParse?.text);
if (date ===null || date==='') return { requiredFromDate: true };
}