<mat-form-field>
<input matInput [(ngModel)]="myDate" name="myDate" [matDatepicker]="Datepicker"
(click)="Datepicker.open()" >
<mat-datepicker-toggle matSuffix [for]="Datepicker"></mat-datepicker-toggle>
<mat-error>Invaild Date</mat-error>
</mat-form-field>
<mat-datepicker #Datepicker></mat-datepicker>
this.form = this.fb.group({
myDate: [this.dateService.dateValidator]
});
dateValidator(control: FormControl) {
console.log(control.value) <<<< problem here
}尊敬的各位:
我尝试将日期值"1“输入到date字段,但是,control.value in dateValidator返回2001-01-01GMT 00:00。它使dateValidator始终传递,即使我填写了"1“到日期字段。如何从"control.value“中获得原始值"1”而不是自动转换的值?谢谢
发布于 2018-08-01 14:50:36
之所以会发生这种情况,是因为它的数据报警器输入的资料是监听程序:
_onInput(value: string) {
let date = this._dateAdapter.parse(value, this._dateFormats.parse.dateInput);和parse()方法这样做吗?
parse(value: any): Date | null {
if (typeof value == 'number') {
return new Date(value);
}因此,当用户在输入中写入1时,场景后面就变成了new Date(1)。
因此,要回答您的问题--“如何才能从"control.value"中获得原始值"1”,您可以对input和change事件都进行过度的记录:
<input matInput
[(ngModel)]="myDate"
name="myDate" [matDatepicker]="Datepicker"
(click)="Datepicker.open()"
(input)="someMethod($event.target.value)"
(change)="someMethod($event.target.value)">发布于 2018-08-01 12:37:41
就像这样:
HTML:
<h1>
Try Reactive Form Validation with custom validation
</h1>
<form [formGroup]="basicForm">
<div>
<input type="text" formControlName="myDate" />
<p *ngIf="basicForm.get('myDate').hasError('required') && basicForm.get('myDate').touched">Required</p>
<p *ngIf="basicForm.get('myDate').hasError('invalidDate')">Invalid Date DD/MM/YYYY</p>
</div>
</form>TS:
basicForm: FormGroup;
ngOnInit() {
this.createForm();
}
constructor(private fb: FormBuilder) {
}
createForm() {
this.basicForm = this.fb.group({
myDate: [null, [Validators.required, CustomValidatorService.dateValidator]]
})
}validation_service.ts:
import { Injectable } from '@angular/core';
import { AbstractControl, FormControl, ValidatorFn } from '@angular/forms';
@Injectable()
export class CustomValidatorService {
constructor() { }
static dateValidator(control: FormControl) {
if (control.value) {
const matches = control.value.match(/^\d{2}\/\d{2}\/\d{4}$/);
return matches ? null : { 'invalidDate': true };
} else {
return null;
}
}
}https://stackoverflow.com/questions/51633047
复制相似问题