【发布时间】:2019-03-13 14:19:15
【问题描述】:
我有两个日期输入 - “开始日期”和“结束日期” - 我还有两个指令用作验证器 - 每个字段的允许最小值和允许最大值(这样开始日期不会晚于结束日期)。 例如,如果我将开始日期更改为晚于结束日期,验证器将提醒它无效。 当我将结束日期从开始日期更改为较晚的日期时 - 此警报不会消失,因为我没有触发“customMax”验证器。 如何在其中一个字段的每次更改时同时触发两个验证器?
谢谢,
输入 HTML:
<input
type="text" class="form-control"
name="startDate{{d.index}}"
required
[customMax]="d.endDate"
(dateChange)="onDateChange('startDate', d.index, $event)"
[(ngModel)]="d.startDate"
appMyDatePicker>
<input type="text" class="form-control"
required
[customMin]="d.startDate"
name="endDate{{d.index}}"
(dateChange)="onDateChange('endDate', d.index, $event)"
[(ngModel)]="d.endDate"
appMyDatePicker>
customMax 指令:
@Directive({
selector: '[appCustomMaxValidator],[customMax][ngModel]',
providers: [{provide: NG_VALIDATORS, useExisting:
CustomMaxValidatorDirective, multi: true}]
})
export class CustomMaxValidatorDirective implements Validator {
@Input()
customMax: Date;
constructor() { }
validate(c: FormControl): {[key: string]: any} {
const maxDateConvertInit = moment(this.customMax, 'DD/MM/YYYY HH:mm:ss').format('DD/MM/YYYY HH:mm:ss');
console.log('cant be greater than:' + maxDateConvertInit);
const maxDateConvertCompare = moment(c.value, 'DD/MM/YYYY HH:mm:ss').format('DD/MM/YYYY HH:mm:ss');
console.log('check date:' + maxDateConvertCompare);
const testScore = (maxDateConvertInit <= maxDateConvertCompare) ? {'customMax': true} : null;
return testScore;
}
}
customMin 指令:
@Directive({
selector: '[appCustomMinValidator],[customMin][ngModel]',
providers: [{provide: NG_VALIDATORS, useExisting: CustomMinValidatorDirective, multi: true}]
})
export class CustomMinValidatorDirective implements Validator {
@Input()
customMin: Date;
constructor() { }
validate(c: FormControl): {[key: string]: any} {
const minDateConvertInit = moment(this.customMin, 'DD/MM/YYYY HH:mm:ss').format('DD/MM/YYYY HH:mm:ss');
const minDateConvertCompare = moment(c.value, 'DD/MM/YYYY HH:mm:ss').format('DD/MM/YYYY HH:mm:ss');
const testScore = (minDateConvertInit >= minDateConvertCompare) ? {'customMin': true} : null;
return testScore;
}
}
【问题讨论】:
标签: angular angular2-directives customvalidator