我正在尝试验证 Angular 2 中的 Reactive 表单字段。在这里我编写了自定义验证器,我不确定这是否是进行验证的正确方法。但是无论如何我没有通过我的代码获得准确的结果,一些测试用例失败了。如果有人知道,请纠正我的代码和方法,如果它是错误的。
这是我的条件,
如果输入通配符,文本字段应为 4 到 14 个字母数字。否则,它是 7 到 25 个字母数字。
一种。如果输入星号 (*),则必须是最后一个字符,并且应该是 5 到 13 个字母数字。
湾 如果输入问号 (?),它可以位于 5 到 14 之间的任何位置。以下文本长度将被接受。
一世。7
ii.10
三.11
四、13
v. 十四
C。如果未输入通配符,则可以是 7 到 25 个字母数字。
这是我的代码,我编写了自定义验证器。
static ProductTypeValidation(min: number, max: number): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null =>{
if(c && (c.value !== '')){
const s=c.value;
var reg=/[^A-Za-z0-9]+/;
var reg1=/[^A-Za-z0-9*?]+/;
if(!s.match(reg)){
if(s.length<7 || s.length>25){
console.log('Invalid with size')
return{
'ProductTypeValidation': true
};
}
else{
console.log('valid with size');
return null;
}
}else{
if(s.match(reg1)){
console.log('Main Error');
return{
'ProductTypeValidation': true
};
}else{
for(let i=0;i<s.length && i<4;i++){
if(s.charAt(i).match(reg)){
console.log('Invalid first');
return{
'ProductTypeValidation': true
};
}else{
console.log('valid');
return null;
}
}
if(s.length>4 && s.length < 14 ){
for(let i=4;i<13;i++){
if(s.charAt(i) == '*'){
if(s.charAt(i+1) == ''){
console.log('valid');
return null;
}else{
console.log('Invalid *');
return{
'ProductTypeValidation': true
};
}
}
}
}
if(s.length>4 && s.length <15){
for(let i=4;i<14;i++){
if(s.charAt(i) == '?'){
if(s.length == 7 || s.length == 10|| s.length == 11 || s.length == 13 || s.length ==14){
console.log('valid');
return null;
}
else{
console.log('Invalid?');
return{
'ProductTypeValidation': true
};
}
}
}
}
for(let i=13;i<s.length && i<25;i++){
if(s.charAt(i).match(reg)){
console.log('Invalid remaining');
return{
'ProductTypeValidation': true
};
}else{
console.log('valid');
return null;
}
}
}
}
}
return null;
};
}
您应该在您的表单控制器中调用自定义验证器,然后您的表单控制器将注意在每次按键时调用您的方法。
'productType': new FormControl('', [CustomValidators.productTypeValidation(6,25)]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句