在一个指令中格式化和验证



我正在尝试构建一个指令来处理处理工期的表单。我希望表单显示时带有一个文本框,其格式为1:24,但总分钟数为144(在这种情况下,这将便于以后添加大量时间!(。

这是我当前的代码:

@Directive({
...
)
export class DurationFormatDirective implements ControlValueAccessor {
@HostBinding('value') inputValue;
mins: number;
onChange;
onTouched;
constructor() {}
@HostListener('blur', ['$event.target.value'])
onBlur(value: string) {
let hrs: number, mins: number;
if (value === '' || value === '0') {
hrs = 0;
mins = 0;
} else {
if (value.indexOf(':') === -1) { // there is no colon
if (value.length <= 2) {
hrs = 0;
mins = +value;
} else {
hrs = +value.substring(0, value.length - 2);
mins = +value.substring(value.length - 2);
}
} else { // There is a colon
const arr = value.split(':');
hrs = +arr[0];
mins = +arr[1];
}
}
this.mins = hrs * 60 + mins;
this.inputValue = `${hrs}:${mins < 10 ? '0' : ''}${mins}`;
this.onChange(this.mins);
this.onTouched();
}
writeValue(val) {
this.mins = val;
const hrs = Math.floor(val / 60);
const mins = val % 60;
this.inputValue = `${hrs}:${mins < 10 ? '0' : ''}${mins}`;
}
registerOnChange(fn) {
this.onChange = fn;
}
registerOnTouched(fn) {
this.onTouched = fn;
}
}

一般来说,这是很好的,但如果用户输入2:zw(例如(,它就会中断,因为zw不是一个数字。如果输入了无效的(IE Not 0-9或:(,则应声明该字段无效,并且不尝试对其进行格式化或更新值。我还可以让这个指令同时更改有效的属性吗。如果有区别的话,我会使用反应形式。

感谢

所以我实际上用不同的方式解决了这个问题。

我添加了RegExp测试来查找字母,并添加了if语句来查找分钟>60。在任何一种情况下,该值都设置为NaN。

然后我创建了一个非常简单的验证器来检查父窗体上的NaN

这也允许我稍后进行另一次验证,检查输入的持续时间是否不大于另一个字段的总持续时间。

指令的完整代码:

@Directive({
selector: '[appTimeFormat]',
})
export class TimeFormatDirective implements ControlValueAccessor {
@HostBinding('value') inputValue;
onChange;
onTouched;
private regex = /^d{1,2}:?d{0,2}$/;
constructor() {}
@HostListener('blur', ['$event.target.value'])
onBlur(value: string) {
this.onTouched();
if (!this.regex.test(value)) {
this.onChange(NaN);
return;
}
let hrs: number, mins: number;
if (value === '' || value === '0') {
hrs = 0;
mins = 0;
} else {
if (value.indexOf(':') === -1) {
// There is no colon
if (value.length <= 2) {
hrs = 0;
mins = +value;
} else {
hrs = +value.substring(0, value.length - 2);
mins = +value.substring(value.length - 2);
}
} else {
// There is a colon
const arr = value.split(':');
hrs = +arr[0];
mins = +arr[1];
}
}
this.inputValue = `${hrs}:${mins < 10 ? '0' : ''}${mins}`;
if (mins > 60) {
this.onChange(NaN);
return;
}
this.onChange(hrs * 60 + mins);
}
writeValue(val) {
if (val) {
const hrs = Math.floor(val / 60);
const mins = val % 60;
this.inputValue = `${hrs}:${mins < 10 ? '0' : ''}${mins}`;
} else {
this.inputValue = '';
}
}
registerOnChange(fn) {
this.onChange = fn;
}
registerOnTouched(fn) {
this.onTouched = fn;
}
}

验证器:

nanValidator(control: FormControl) {
if (isNaN(control.value)) {
return { invalidNumber: true };
}
return null;
}

最新更新