javascriptangularangular-reactive-formscustom-validators

Custom validator for "Optional Field" Angular 2 Reactive forms


I wrote a custom validator for the "Optional" field, and the logic and validations work well with the corresponding value. But once the text field is clicked and it does not provide the value it will show as a mandatory field. If any one knows please help me out.

This is my custom validator class. Here my text field value would be like '123s,wd345,23' and range(2,12)

custom-validator.ts

import { AbstractControl, ValidatorFn } from '@angular/forms';

export class OrderUnitValidators {

  static range(min: number, max: number): ValidatorFn {
      return (c: AbstractControl): { [key: string]: boolean } | null => {
          if(c && (c.value !==null || c.value !== undefined)){
            const str=c.value;
            const valArr=str.split(',');
            for(let val in valArr){
                if(valArr[val].length<2 || valArr[val].length>12){
                return { 
                    'range' : true
                     };
                }
          
            }
        }
        
        return null;
      };
  }
}


Solution

  • As Florian said,you did a small mistake, I had tested your code it's working perfectly for me. But make sure that in FormGroup you should initialize empty string.

    export class OrderUnitValidators {
    
      static range(min: number, max: number): ValidatorFn {
          return (c: AbstractControl): { [key: string]: boolean } | null => {
              if(c && (c.value !== '')){
                const str=c.value;
                const valArr=str.split(',');
                for(let val in valArr){
                    
                    if(valArr[val].length<2 || valArr[val].length>12){
                    return { 
                        'range' : true
                         };
                    }
              
                }
            }
            
            return null;
          };
      }
    }