What is the best way to validate reactive form field in Angular2?

173 Views Asked by At

I am trying to validate Reactive form field in Angular 2. Here i have written custom validator, I am not sure whether this is right approach to do validation. But any how i am not getting accurate result through my code, some of the test cases are failed. If any one knows please correct me the code as well as approach, if it is wrong.

These are my conditions,

  1. Text field should be 4 to 14 alphanumeric if wildcards are entered. Otherwise it is 7 to 25 alphanumeric.

    a. If asterisk (*) is entered, that must be the last character and should be 5 to 13 alphanumerics.

    b. If question mark (?) is entered, it can be in any position between5 and 14 inclusive. It would be accepted for the following text length.

    i. 7

    ii.10

    iii.11

    iv. 13

    v. 14

    c. If wildcards are not entered, it can be 7 to 25 alphanumeric s.

This is my code, which i have written custom validator.

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; 
  };
}

2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER

You should call custom validator in your Form controller, then your form controller will take care to call your method each key press.

'productType': new FormControl('', [CustomValidators.productTypeValidation(6,25)]);

0
Roy On

I finished writing 'custom validator' for the aforementioned circumstances, but when I call it from the project, it is only valid for the first key press, even though it is a function that gives me the correct result when testing differently.Can any one please correct me.

Here is my updated code.

//Custom validator for Product type
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*?]+/;
    var reg2=/[^A-Za-z0-9*]+/;
    var reg3=/[^A-Za-z0-9?]+/;
    if(s.match(reg))
    {
      if(s.match(reg1))
      {
        console.log('Apart from special char existed')
        return{
          'ProductTypeValidation': true
        };
      }else{
            if(s.length < 4)
            {
                console.log('special char existed but length is minimum');
                return{
                  'ProductTypeValidation': true
                };
            }else{
                    if(s.charAt(0).match(reg) || s.charAt(1).match(reg) || s.charAt(2).match(reg) || s.charAt(3).match(reg))
                    {
                         console.log('first 4 positions it self special char existed');
                         return{
                          'ProductTypeValidation': true
                        };
                    }else{
                            if(s.length>4 && s.length<=14)
                            {
                                 if(s.match(reg2) && s.match(reg3))
                                 {
                                     let a=s.indexOf('*');
                                     let b=s.indexOf('?');
                                    if(b>a)
                                    {
                                        console.log('Invalid after * everything is invalid');
                                        return{
                                          'ProductTypeValidation': true
                                        };
                                    }else if((s.charAt(a+1) == '') && (s.length == 7 ||s.length == 10 || s.length == 11 ||s.length == 13 || s.length == 14) && (a<13))
                                    {
                                        
                                        console.log('valid with all conditions * and ?');
                                        return null;
                                    }else{
                                        console.log('Invalid ? and *');
                                        return{
                                          'ProductTypeValidation': true
                                        };
                                         }
                                 }
                                else if(s.match(reg2))
                                 {
                                     if(s.length == 7 || s.length ==10 || s.length == 11 || s.length == 13 || s.length == 14)
                                     {
                                         console.log('valid with ?');
                                         return null;
                                    }else{
                                     console.log('invalid with ?');
                                     return{
                                      'ProductTypeValidation': true
                                    };
                                    }
                                 }else{
                                    let a=s.indexOf('*');
                                    let b=s.indexOf('?');
                                    if(s.length>4 && s.length <14)
                                    {

                                    if(b>a)
                                    {
                                        console.log('Invalid after * everything is invalid');
                                        return{
                                          'ProductTypeValidation': true
                                        };
                                     }else if(s.charAt(a+1) == '')
                                     {
                                        console.log('vaid with *');
                                        return null;
                                    }else{
                                         console.log('Invalid with *');
                                         return{
                                          'ProductTypeValidation': true
                                        };
                                        }
                                    }else{
                                      console.log('* exceeded the size');
                                      return{
                                        'ProductTypeValidation': true
                                      };
                                    }
                                  }

            
                             }else{
                                    if(s.match(reg))
                                    {
                                    console.log('After 14 no special characters are allowed');
                                    return{
                                      'ProductTypeValidation': true
                                    };
                                    }else{
                                    console.log('it will return null');
                                    return null;
                                    }
  
                                }
                        }
                }
            }
      
    }else{
      if(s.length<7 || s.length>25){
        console.log('size not matched');
        return{
          'ProductTypeValidation': true
        };
      }else{
        console.log('Size matched');
        return null;
      }
    }
      
}
return null;

}
}