【发布时间】:2018-07-28 21:28:06
【问题描述】:
我正在尝试验证 Angular 2 中的响应式表单字段。我在这里编写了自定义验证器,我不确定这是否是正确的验证方法。但是无论我如何通过我的代码没有得到准确的结果,一些测试用例都失败了。如果有人知道,请纠正我的代码以及方法,如果有错误。
这是我的条件,
-
如果输入通配符,文本字段应为 4 到 14 个字母数字。否则为 7 到 25 个字母数字。
一个。如果输入星号 (*),则必须是最后一个字符,并且应该是 5 到 13 个字母数字。
b.如果输入问号 (?),它可以在 5 到 14 之间的任何位置。以下文本长度将被接受。
我。 7
ii.10
iii.11
四。 13
v. 14
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;
};
}
【问题讨论】:
标签: javascript angular validation angular-reactive-forms custom-validators