交互1 :禁止输入-或.
@ViewChild('rowInput', { static: false }) rowInput: ElementRef;
//如果在ngOnInit不能获取lineInput.nativeElement可以改用ngAfterViewInit钩子函数
ngOnInit() {
var lineEle = this.lineInput.nativeElement;
rowEle.addEventListener("keydown", (e: any) => this.onRowKeyDown(e), false);
}
onRowKeyDown(event: any) {
if (event.key == '-' || event.key == '.' || event.key == 'e') {
event.preventDefault();
var message = this.ValidationMessages['rowControl'];//错误提示显示
this.FormErrors['rowControl'] = message['onlyNumber'];
}
}
交互2:自定义validator
定义一个只能输入0-9的validator
import {FormControl, ValidatorFn, AbstractControl} from "@angular/forms";
export function onlyPositiveIntegerCheck(control: FormControl): any {
if(control.value == null || control.value === ""){
return null;
}
var myreg = /^[0-9]*$/;
var valid = myreg.test(control.value);
return valid ? null : { onlyNumber: true };//返回null代表校验通过
}
2调用
initFromGroup() {
this.customLayoutForm = this.fb.group({
rowControl: ['', [Validators.required, Validators.max(6), Validators.min(1),onlyPositiveIntegerCheck]],
lineControl: ['', [Validators.required, Validators.max(6), Validators.min(1)]],
});
this.customLayoutForm.controls.rowControl.valueChanges.subscribe((data)=>{this.onValueChanged(data)});
this.customLayoutForm.controls.lineControl.valueChanges.subscribe((data)=>{this.onValueChanged(data)});
}
onValueChanged(data?: any) {
if (!this.customLayoutForm || !this.customLayoutForm.dirty) {
return;
}
for (const field in this.FormErrors) {
this.FormErrors[field] = '';
const control = this.customLayoutForm.get(field);
if (control && control.dirty && control.invalid) {
const message = this.ValidationMessages[field];
for (const key in control.errors) {
this.FormErrors[field] += message[key] + '';
break;//取第一个错误
}
}
}
}
public ValidationMessages = {
rowControl: {
required: "此项为必填项",
max: "最大值为6",
min: "最小值为1",
onlyNumber:"请输入整数"
},
lineControl: {
required: "此项为必填项",
max: "最大值为6",
min: "最小值为1",
onlyNumber:"请输入整数"
},
}