all files / src/ ng-selector.validator.ts

100% Statements 16/16
100% Branches 15/15
100% Functions 3/3
100% Lines 14/14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28                            
import { Directive } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator } from '@angular/forms';
 
@Directive({
    selector: 'ng-selector[required][ngModel]',
    providers: [{ provide: NG_VALIDATORS, useClass: NgSelectorValidator, multi: true }]
})
export class NgSelectorValidator implements Validator {
    validate (c: AbstractControl): { [p: string]: any } {
        return this.isEmpty(c.value) ? { required: { valid: false } } : null;
    }
 
    private isEmpty (value: any) {
        if (value === null || value === undefined) {
            return true;
        }
        // empty array
        if (Array.isArray(value) && value.length > 0) {
            return false;
        }
        // all objects are valids
        if (!Array.isArray(value) && typeof value === 'object' && Object.keys(value).length > 0) {
          return false;
        }
        return true;
    }
}