我正在尝试实现用于日期范围检查的自定义角度验证器。
验证器本身可以正常工作,并返回验证错误。但是,客户端似乎什么也没发生-没有错误显示,并且该表格被认为是有效的。我已经尝试过对此代码进行各种更改,没有任何乐趣。
有什么想法可以尝试吗?
HTML:
<div class="alert-danger" *ngIf="form.controls.creditCheckDate.errors?.dateRange">
Date should be from 1/1/2000 to Today.
</div>
.ts:
const controlsConfig = {
creditCheckDate: ['', [Validators.required,
CustomValidators.dateRange(new Date(2000, 1), new Date(Date.now()))]]
};
return this.fb.group(controlsConfig);
验证者:
static dateRange(minDate: Date | null, maxDate: Date | null): ValidatorFn {
return (c: AbstractControl): ValidationErrors | null => {
const validationError = { dateRange: true };
if (!c.value) {
return null;
}
const timestamp = Date.parse(c.value);
if (isNaN(timestamp)) {
return validationError;
}
const date = new Date(timestamp);
if ((minDate && minDate > date) || (maxDate && maxDate < date)) {
return validationError;
}
return null;
};
}
答案 0 :(得分:2)
请查看我的代码。
<form [formGroup]="testForm">
<div class="row">
<div class="col-xs-12 col-12 col-md-4 form-group">
<input
type="text"
placeholder="Datepicker"
class="form-control"
bsDatepicker
formControlName = "date"
/>
</div>
<div *ngIf="testForm.controls.date.invalid && (submitted)" class="text-danger">
<small *ngIf="testForm.controls.date.errors?.required">
Date is required
</small>
<small *ngIf="testForm.controls.date.errors?.dateRange">
Date is invalid
</small>
</div>
</div>
<button type="button" (click)="onSubmit()">Submit</button>
</form>
import { Component } from "@angular/core";
import {
AbstractControl,
FormGroup,
FormControl,
ValidationErrors,
ValidatorFn,
Validators
} from "@angular/forms";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
testForm: FormGroup;
submitted: boolean;
constructor() {
this.testForm = new FormGroup({
date: new FormControl("", [Validators.required, this.dateRange(new Date(2000, 1), new Date(Date.now()))])
});
this.submitted = false;
}
dateRange(minDate: Date | null, maxDate: Date | null): ValidatorFn {
return (c: AbstractControl): ValidationErrors | null => {
const validationError = { dateRange: true };
if (!c.value) {
return null;
}
const timestamp = Date.parse(c.value);
if (isNaN(timestamp)) {
return validationError;
}
const date = new Date(timestamp);
if ((minDate && minDate > date) || (maxDate && maxDate < date)) {
return validationError;
}
return null;
};
}
onSubmit() {
this.submitted = true;
console.log(this.testForm);
}
}
我已经在代码沙箱中尝试过您的代码,并且看起来工作正常。 https://codesandbox.io/s/suspicious-http-11288
答案 1 :(得分:0)
因此,事实证明我没有提供所有信息。问题是有人在其他验证程序中重置了该表格的所有错误。这是一种糟糕的处理方式,因为我已经很长时间找不到了,但是它在那里。当我找到并修复它后,一切开始按预期工作。