Angular 组件中定义了以下函数:
handleInput(event) {
// Validate the input
if (event.target.value.length >= 8) {
this.validate(event.target.value);
}
}
// Validation logic for provider NG_VALIDATORS will
// Logic for NG_VALIDATORS provider, returns validation result to parent form
/** @internal */
validate(control) {
const value = control.value || control;
if (this.required && value.replace(/\s+/g, '').length === 0) {
this.hasError = this.control.touched || this.control.dirty;
this.errorText = [{ message: this.requiredErrorMessage }];
return this.required ? { required: 'date required' } : null;
}
if (!value) {
this.hasError = false;
return null;
}
const [day, month, year] = value.split('.').map(Number);
if (day && month && year && value.length === 10) {
const date = new Date(year, month - 1, day);
const isDateValid = !isNaN(date.getTime()) && date.getFullYear() === year && date.getMonth() + 1 === month && date.getDate() === day;
this.hasError = !isDateValid || date > this.maxDate || date < this.minDate;
if (this.hasError) {
this.hasError = true;
this.errorText = [{ message: this.validationErrorMessage }];
return { invalid: 'date invalid' };
}
}
this.hasError = false;
return null;
}
这是对应的自定义输入字段:
<input
#input
type="text"
mask="00.00.0000"
autocomplete="off"
(input)="handleInput($event)"
[(ngModel)]="value"
/>
输入字段将使用 ngx-mask 添加 DD.MM.YYYY 格式的日期字段的掩码。
问题:
组件渲染时,抛出以下错误:
错误类型错误:value.split不是函数
对于这行代码:
const [day, month, year] = value.split('.').map(Number);
我已经尝试用
修复它if (!value) {
this.hasError = false;
return null;
}
如果在输入字段中输入了字符串,然后输入已被删除(空输入字段),则在渲染组件时会显示错误。
无需在
input
事件上调用验证函数。它将被角度内部自动调用。因此,请专注于调用您注册的 onChange
方法,并将控件标记为触摸。
onChange = (quantity) => {};
onTouched = () => {};
registerOnChange(onChange: any) {
this.onChange = onChange;
}
registerOnTouched(onTouched: any) {
this.onTouched = onTouched;
}
markAsTouched() {
if (!this.touched) {
this.onTouched();
this.touched = true;
}
}
// change events from the textarea
private handleInput(event: any) {
this.markAsTouched();
this.onChange(event.target.value);
}