All files / src/utils/validation/validators/field RequiredValidator.ts

100% Statements 13/13
92.31% Branches 12/13
100% Functions 2/2
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48  5x               5x             2x   2x     2x   2x               2x   2x   2x   1x     2x   1x     2x    
import { ValidatorOptions } from "../Validator";
import SingleValueFieldValidator, { SingleValueFieldValidationContext } from "./SingleValueFieldValidator";
 
export interface RequiredValidatorOptions extends ValidatorOptions {
 
    /** If true, allows '' as a valid value */
    allowEmpty?: boolean;
}
 
export default class RequiredValidator extends SingleValueFieldValidator {
 
    /** If true, allows '' as a valid value */
    allowEmpty: boolean;
 
    constructor(options: RequiredValidatorOptions = {}) {
 
        Eif (options.message === undefined) {
 
            options.message ='{{label}} is required';
        }
 
        super(options);
 
        this.allowEmpty = options.allowEmpty || false;
    }
 
    validate(context: SingleValueFieldValidationContext): boolean {
 
        const {
            label,
            value
        } = context;
 
        var valid = !(value === undefined || value === null);
 
        if (valid === true && this.allowEmpty === false) {
 
            valid = value !== '';
        }
 
        if (!valid) {
 
            this.emitErrors(context, { label });
        }
 
        return valid;
    }
}