| 6 | import { ExistsOptions, Validators } from './validators'; |
| 7 | |
| 8 | export class ValidatorsImpl<Chain> implements Validators<Chain> { |
| 9 | private lastValidator: CustomValidation | StandardValidation; |
| 10 | private negateNext = false; |
| 11 | |
| 12 | constructor(private readonly builder: ContextBuilder, private readonly chain: Chain) {} |
| 13 | |
| 14 | private addItem(item: CustomValidation | StandardValidation) { |
| 15 | this.builder.addItem(item); |
| 16 | this.lastValidator = item; |
| 17 | // Reset this.negateNext so that next validation isn't negated too |
| 18 | this.negateNext = false; |
| 19 | |
| 20 | return this.chain; |
| 21 | } |
| 22 | |
| 23 | // validation manipulation |
| 24 | not() { |
| 25 | this.negateNext = true; |
| 26 | return this.chain; |
| 27 | } |
| 28 | |
| 29 | withMessage(message: FieldMessageFactory | ErrorMessage) { |
| 30 | this.lastValidator.message = message; |
| 31 | return this.chain; |
| 32 | } |
| 33 | |
| 34 | // custom validators |
| 35 | custom(validator: CustomValidator) { |
| 36 | return this.addItem(new CustomValidation(validator, this.negateNext)); |
| 37 | } |
| 38 | |
| 39 | exists(options: ExistsOptions = {}) { |
| 40 | let validator: CustomValidator; |
| 41 | if (options.checkFalsy || options.values === 'falsy') { |
| 42 | validator = value => !!value; |
| 43 | } else if (options.checkNull || options.values === 'null') { |
| 44 | validator = value => value != null; |
| 45 | } else { |
| 46 | validator = value => value !== undefined; |
| 47 | } |
| 48 | |
| 49 | return this.custom(validator); |
| 50 | } |
| 51 | |
| 52 | isArray(options: { min?: number; max?: number } = {}) { |
| 53 | return this.custom( |
| 54 | value => |
| 55 | Array.isArray(value) && |
| 56 | (typeof options.min === 'undefined' || value.length >= options.min) && |
| 57 | (typeof options.max === 'undefined' || value.length <= options.max), |
| 58 | ); |
| 59 | } |
| 60 | |
| 61 | isObject(options: { strict?: boolean } = { strict: true }) { |
| 62 | return this.custom( |
| 63 | value => |
| 64 | typeof value === 'object' && |
| 65 | (options.strict == null || options.strict ? value !== null && !Array.isArray(value) : true), |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…