Javascript 自定义验证器没有为Angular 2中的每个按键调用
我在Angular 2中为被动表单编写了一个自定义验证器。但是我的功能是只验证文本字段中的第一次按键。这里我的自定义函数应该验证每个按键。谁能纠正我一下吗 这就是我在类中调用自定义函数的方式Javascript 自定义验证器没有为Angular 2中的每个按键调用,javascript,angular,validation,angular-reactive-forms,custom-validators,Javascript,Angular,Validation,Angular Reactive Forms,Custom Validators,我在Angular 2中为被动表单编写了一个自定义验证器。但是我的功能是只验证文本字段中的第一次按键。这里我的自定义函数应该验证每个按键。谁能纠正我一下吗 这就是我在类中调用自定义函数的方式 'customerNumberOwner': new FormControl('', [CustomValidators.CustomerNumberCustomValidation(6,8)]), 这是我的自定义函数 //客户编号所有者的自定义验证程序 静态CustomerNumber Custo
'customerNumberOwner': new FormControl('', [CustomValidators.CustomerNumberCustomValidation(6,8)]),
这是我的自定义函数
//客户编号所有者的自定义验证程序
静态CustomerNumber CustomValidation(最小:编号,最大:编号):Validator fn{
return(c:AbstractControl):{[key:string]:boolean}| null=>{
var reg=/[^A-Za-z0-9]+/;
如果(c&&(c.值!=''){
const str=c.值;
if(str.match(reg)| | str.lengthmax){
console.log('无效')
返回{
“CustomerNumber CustomValidation”:true
};
}
}
返回null;
};
}
我希望这会有所帮助
HTML:
custom-validator.service.ts:
import { Injectable } from '@angular/core';
import { AbstractControl, FormControl, ValidatorFn } from '@angular/forms';
@Injectable()
export class CustomValidatorService {
constructor() { }
static CustomerNumberCustomValidation(control: FormControl) {
var reg = /[^A-Za-z0-9]+/;
if (control.value) {
const matches = control.value.match(reg);
return matches ? null : { 'CustomerNumberCustomValidation': true };
} else {
return null;
}
}
}
你怎么知道的?您是否对其进行了console.log()操作?如果是,在代码的哪一行?在中使用chrome调试器工具进行调试。你肯定会得到一些东西。@Lynx在这里他们的函数没有问题,它不是每次按键都调用的。
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CustomValidatorService } from './custom-validator.service'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
basicForm: FormGroup;
ngOnInit() {
this.createForm();
}
constructor(private fb: FormBuilder) {
}
createForm() {
this.basicForm = this.fb.group({
name: this.fb.control(null, [Validators.required, Validators.minLength(10), CustomValidatorService.CustomerNumberCustomValidation])
})
}
}
import { Injectable } from '@angular/core';
import { AbstractControl, FormControl, ValidatorFn } from '@angular/forms';
@Injectable()
export class CustomValidatorService {
constructor() { }
static CustomerNumberCustomValidation(control: FormControl) {
var reg = /[^A-Za-z0-9]+/;
if (control.value) {
const matches = control.value.match(reg);
return matches ? null : { 'CustomerNumberCustomValidation': true };
} else {
return null;
}
}
}