Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

policeman

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

policeman - npm Package Compare versions

Comparing version 0.1.0 to 0.2.0

7

CHANGELOG.md
# CHANGELOG
## 0.2.0
* Errors format corresponds to validation format ([more](src/test/policeman.test.ts))
* Direct validators import i.e. `import { isEmail } from "policeman"`
* Rename maxLength and minLength to isMaxLength and isMinLength
* Add isEqualLength validator
## 0.1.0

@@ -4,0 +11,0 @@

32

lib/policeman.d.ts

@@ -1,17 +0,9 @@

import { Source, Result, Filter } from "mappet";
export interface Message {
(value: any): string;
export interface Filter {
(value: any, source: Object): boolean;
}
export interface EntryValidator {
(value: any): string;
export interface Validator {
(value: any, source: Object): string;
}
export interface SchemaValidator {
(source: Source): {
errors: Result;
valid: boolean;
};
}
export declare type BasicSchemaEntry = [string, string, EntryValidator[]];
export declare type FilterableSchemaEntry = [string, string, EntryValidator[], Filter];
export declare type Schema = [BasicSchemaEntry | FilterableSchemaEntry];
export declare type Validate = Validator | Validator[];
export declare type Schema = Array<[string, string, Validate] | [string, string, Validate, Filter]>;
/**

@@ -22,2 +14,12 @@ * Produce validator based on provided schema

*/
export default function policeman(schema: Schema): SchemaValidator;
export default function policeman(schema: Schema): (source: Object) => {
errors: any;
valid: boolean;
};
/**
* Combines list of validators passed as params into single validator
*
* @returns Validator capable of performing multiple validations, returning first error
*/
export declare function combineValidators(...validators: Validator[]): Validator;
export * from "./validators";
"use strict";
var get = require("lodash/get");
var mappet_1 = require("mappet");
function buildModifier(validators) {
return function (value, source) { return validators
.map(function (validator) { return validator(value); })
.filter(function (error) { return error !== null; }); };
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function checkValidity(schema, errors) {
return schema.reduce(function (valid, _a) {
var dest = _a[0];
var err = get(errors, dest);
return valid && (err === undefined || get(errors, dest).length === 0);
}, true);
const get = require("lodash/get");
const set = require("lodash/set");
/**
* Default filter function which accepts each entry
*/
function always(...args) {
return true;
}
/**
* Apply validator for specified value and source
*/
function applyValidators(value, source, validators) {
return validators.map(validator => validator(value, source)).filter(Boolean);
}
function appendValue(source, errorPath, sourcePath, validate, filter = always) {
const value = get(source, sourcePath);
return [errorPath, sourcePath, validate, filter, value];
}
function omitByFilter(source, errorPath, sourcePath, validate, filter, value) {
return filter(value, source);
}
function validateToErrors(source, errorPath, sourcePath, validate, filter, value) {
if (validate instanceof Array) {
const errors = applyValidators(value, source, validate);
const valid = !errors.length;
return [errorPath, errors, valid];
}
else {
const error = validate(value, source);
const valid = error === null;
return [errorPath, error, valid];
}
}
/**
* Produce validator based on provided schema

@@ -22,10 +44,9 @@ *

function policeman(schema) {
var validationSchema = schema
.map(function (_a) {
var dest = _a[0], source = _a[1], validators = _a[2], filter = _a[3];
return [dest, source, buildModifier(validators), filter];
});
return function (source) {
var errors = mappet_1.default(validationSchema)(source);
var valid = checkValidity(schema, errors);
return (source) => {
const validated = schema
.map(entry => appendValue.apply(null, [source, ...entry]))
.filter(entry => omitByFilter.apply(null, [source, ...entry]))
.map(entry => validateToErrors.apply(null, [source, ...entry]));
const errors = validated.reduce((errs, [errorPath, error]) => set(errs, errorPath, error), {});
const valid = !validated.find(([_errorPath, _error, correct]) => !correct);
return { errors: errors, valid: valid };

@@ -36,2 +57,12 @@ };

exports.default = policeman;
/**
* Combines list of validators passed as params into single validator
*
* @returns Validator capable of performing multiple validations, returning first error
*/
function combineValidators(...validators) {
return (value, source) => applyValidators(value, source, validators)[0];
}
exports.combineValidators = combineValidators;
__export(require("./validators"));
//# sourceMappingURL=policeman.js.map

@@ -1,7 +0,7 @@

import { Message } from "./policeman";
export declare const isRequired: _.CurriedFunction2<Message, string | boolean, string>;
export declare const minLength: _.CurriedFunction3<number, Message, string, string>;
export declare const maxLength: _.CurriedFunction3<number, Message, string, string>;
export declare const isEmail: _.CurriedFunction2<Message, string, string>;
export declare const isMatching: _.CurriedFunction3<RegExp, Message, string, string>;
export declare const isPassing: _.CurriedFunction3<(value: any) => boolean, Message, string, string>;
export declare const isRequired: _.CurriedFunction2<(value: any) => string, string | boolean, string>;
export declare const isMinLength: _.CurriedFunction3<number, (value: any) => string, string, string>;
export declare const isMaxLength: _.CurriedFunction3<number, (value: any) => string, string, string>;
export declare const isEqualLength: _.CurriedFunction3<number, (value: any) => string, string, string>;
export declare const isEmail: _.CurriedFunction2<(value: any) => string, string, string>;
export declare const isMatching: _.CurriedFunction3<RegExp, (value: any) => string, string, string>;
export declare const isPassing: _.CurriedFunction3<(value: any) => boolean, (value: any) => string, string, string>;
"use strict";
var curry = require("lodash/curry");
exports.isRequired = curry(function (message, value) {
var valid = value !== null && value !== undefined && value !== "" && value;
const curry = require("lodash/curry");
exports.isRequired = curry((message, value) => {
const valid = value !== null && value !== undefined && value !== "";
return valid ? null : message(value);
});
exports.minLength = curry(function (min, message, value) {
var valid = value.length >= min;
exports.isMinLength = curry((min, message, value) => {
const valid = value.length >= min;
return valid ? null : message(value);
});
exports.maxLength = curry(function (max, message, value) {
var valid = value.length <= max;
exports.isMaxLength = curry((max, message, value) => {
const valid = value.length <= max;
return valid ? null : message(value);
});
exports.isEmail = curry(function (message, value) {
var valid = /^[a-z0-9_\-\.]{2,}@[a-z0-9_\-\.]{2,}\.[a-z]{2,}$/i.test(value);
exports.isEqualLength = curry((equal, message, value) => {
const valid = value.length === equal;
return valid ? null : message(value);
});
exports.isMatching = curry(function (regexp, message, value) {
var valid = regexp.test(value);
exports.isEmail = curry((message, value) => {
const valid = /^[a-z0-9_\-\.]{2,}@[a-z0-9_\-\.]{2,}\.[a-z]{2,}$/i.test(value);
return valid ? null : message(value);
});
exports.isPassing = curry(function (predicate, message, value) {
var valid = predicate(value);
exports.isMatching = curry((regexp, message, value) => {
const valid = regexp.test(value);
return valid ? null : message(value);
});
exports.isPassing = curry((predicate, message, value) => {
const valid = predicate(value);
return valid ? null : message(value);
});
//# sourceMappingURL=validators.js.map
{
"name": "policeman",
"version": "0.1.0",
"version": "0.2.0",
"description": "Lightweight yet powerful schema validator",

@@ -40,5 +40,4 @@ "main": "lib/policeman.js",

"dependencies": {
"lodash": "^4.15.0",
"mappet": "^2.0.0"
"lodash": "^4.15.0"
}
}

@@ -22,23 +22,30 @@ # policeman

### `isRequired(message, value)`
All built-in validator are [curried](https://lodash.com/docs#curry).
Validates presence.
### `isRequired(() => message, value)`
### `minLength(min, message, value)`
Validates presence. Fails on `null`, empty string or `undefined`.
### `isMinLength(min, () => message, value)`
Passed `value` must be a string longer or with length equal to `min`.
### `maxLength(max, message, value)`
### `isMaxLength(max, () => message, value)`
Passed `value` must be a string shorther or with length equal to `max`.
### `isEmail(message, value)`
### `isEqualLength(equal, () => message, value)`
Passed `value` must be a valid email.
Passed `value` must be a string shorther or with length equal to `max`.
### `isMatching(regexp, message, value)`
### `isEmail(() => message, value)`
Passed `value` must be a valid email. It's a simple check, if you need more complex solution use
`isMatching` or `isPassing`.
### `isMatching(regexp, () => message, value)`
Passed `value` must pass `regexp`.
### `isPassing(predicate, message, value)`
### `isPassing(predicate, () => message, value)`

@@ -48,2 +55,13 @@ Passed `predicate` answers on "Is `value` valid?". When `predicate` returns `true` validator passes,

It makes `policeman` compatible with all available validators i.e. [validator](https://www.npmjs.com/package/validator).
```js
import validator from "validator";
import { isPassing } from "policeman";
const isCreditCard = isPassing(validator.isCreditCard, () => "is invalid credit card");
const isUUID4 = isPassing(value => validator.isUUID(value, 4), () => "is invalid UUID v4");
const isFTP = isPassing(value => validator.isURL(value, { protocols: ["ftp"] }, () => "is invalid FTP address");
```
See [tests](src/test/validators.test.ts) for more examples.

@@ -56,1 +74,6 @@

See [tests](src/test/policeman.test.ts) for more examples.
## Roadmap
* Improve importing validators
* Maybe (monad) error?
import * as get from "lodash/get";
import mappet, { Source, Result, Modifier, Filter, Schema as MappetSchema } from "mappet";
import * as set from "lodash/set";
export interface Message {
(value: any): string;
export interface Filter {
(value: any, source: Object): boolean;
}
export interface EntryValidator {
(value: any): string;
export interface Validator {
(value: any, source: Object): string;
}
export interface SchemaValidator {
(source: Source): { errors: Result, valid: boolean };
export type Validate = Validator | Validator[];
type Error = string | string[];
/**
* Default filter function which accepts each entry
*/
function always(...args: Array<any>): boolean {
return true;
}
export type BasicSchemaEntry = [string, string, EntryValidator[]];
export type FilterableSchemaEntry = [string, string, EntryValidator[], Filter];
export type Schema = [BasicSchemaEntry | FilterableSchemaEntry];
/**
* Apply validator for specified value and source
*/
function applyValidators(value: any, source: Object, validators: Validator[]) {
return validators.map(validator => validator(value, source)).filter(Boolean);
}
function buildModifier(validators: EntryValidator[]): Modifier {
return (value, source) => validators
.map(validator => validator(value))
.filter(error => error !== null);
function appendValue(
source: Object,
errorPath: string,
sourcePath: string,
validate: Validate,
filter: Filter = always
): [string, string, Validate, Filter, any] {
const value = get(source, sourcePath);
return [errorPath, sourcePath, validate, filter, value];
}
function checkValidity(schema: Schema, errors: Source): boolean {
return schema.reduce((valid, [dest]) => {
const err = get(errors, dest);
return valid && (err === undefined || (<string[]> get(errors, dest)).length === 0);
}, true);
function omitByFilter(
source: Object,
errorPath: string,
sourcePath: string,
validate: Validate,
filter: Filter,
value: any
): boolean {
return filter(value, source);
}
function validateToErrors(
source: Object,
errorPath: string,
sourcePath: string,
validate: Validate,
filter: Filter,
value: any
): [string, Error, boolean] {
if (validate instanceof Array) {
const errors = applyValidators(value, source, validate);
const valid = !errors.length;
return [errorPath, errors, valid];
} else {
const error = validate(value, source);
const valid = error === null;
return [errorPath, error, valid];
}
}
export type Schema = Array<[string, string, Validate] | [string, string, Validate, Filter]>;
/**

@@ -38,12 +77,25 @@ * Produce validator based on provided schema

*/
export default function policeman(schema: Schema): SchemaValidator {
const validationSchema = <MappetSchema> schema
.map(<FilterableSchemaEntry>([dest, source, validators, filter]) =>
[dest, source, buildModifier(validators), filter]);
export default function policeman(schema: Schema) {
return (source: Object) => {
const validated = schema
.map(entry => appendValue.apply(null, [source, ...entry]))
.filter(entry => omitByFilter.apply(null, [source, ...entry]))
.map(entry => validateToErrors.apply(null, [source, ...entry]));
return (source: Source) => {
const errors = mappet(validationSchema)(source);
const valid = checkValidity(schema, errors);
const errors = validated.reduce((errs: Object, [errorPath, error]) => set(errs, errorPath, error), {});
const valid = !validated.find(([_errorPath, _error, correct]) => !correct);
return { errors, valid };
};
}
/**
* Combines list of validators passed as params into single validator
*
* @returns Validator capable of performing multiple validations, returning first error
*/
export function combineValidators(...validators: Validator[]): Validator {
return (value: any, source: Object) => applyValidators(value, source, validators)[0];
}
export * from "./validators";
import * as curry from "lodash/curry";
import { Message } from "./policeman";
type Message = (value: any) => string;
export const isRequired = curry((message: Message, value: string | boolean) => {
const valid = value !== null && value !== undefined && value !== "" && value;
const valid = value !== null && value !== undefined && value !== "";
return valid ? null : message(value);
});
export const minLength = curry((min: number, message: Message, value: string) => {
export const isMinLength = curry((min: number, message: Message, value: string) => {
const valid = value.length >= min;

@@ -14,3 +15,3 @@ return valid ? null : message(value);

export const maxLength = curry((max: number, message: Message, value: string) => {
export const isMaxLength = curry((max: number, message: Message, value: string) => {
const valid = value.length <= max;

@@ -20,2 +21,7 @@ return valid ? null : message(value);

export const isEqualLength = curry((equal: number, message: Message, value: string) => {
const valid = value.length === equal;
return valid ? null : message(value);
});
export const isEmail = curry((message: Message, value: string) => {

@@ -22,0 +28,0 @@ const valid = /^[a-z0-9_\-\.]{2,}@[a-z0-9_\-\.]{2,}\.[a-z]{2,}$/i.test(value);

import * as tape from "tape";
import { Filter } from "mappet";
import policeman, { Schema } from "../lib/policeman";
import { isRequired, minLength } from "../lib/validators";
import policeman, { combineValidators, Filter } from "../lib/policeman";
import { isRequired, isEmail } from "../lib/validators";
function returnsErrorObjects(t: tape.Test) {
const required = isRequired(() => "is required");
const minLength20 = minLength(20)(() => "should contain at least 10 characters");
type Test = tape.Test;
const schema: Schema = [
["firstName", "personal.first_name", [required]],
["lastName", "personal.last_name", [required]],
["other.bio", "bio", [required, minLength20]],
];
const validator = policeman(schema);
const source = {
personal: {
first_name: "Foo",
function appliesSignleValidator(t: Test) {
const requiredCheck = isRequired(() => "is required");
const validator = policeman([
["fullName", "full_name", requiredCheck],
]);
const actual = validator({});
const expected = {
valid: false,
errors: {
fullName: "is required",
},
bio: "Lorem ipsum",
};
t.deepEqual(actual, expected, "results in single error if single validator was specified");
}
function appliesMultipleValidators(t: Test) {
const requiredCheck = isRequired(() => "is required");
const emailCheck = isEmail(() => "is invalid email");
const validator = policeman([
["email", "email", [requiredCheck, emailCheck]],
]);
const actual = validator({});
const expected = {
firstName: <any[]> [],
lastName: ["is required"],
other: {
bio: ["should contain at least 10 characters"],
valid: false,
errors: {
email: ["is required", "is invalid email"],
},
};
const { errors } = validator(source);
t.deepEqual(errors, expected, "validator returns errors object defined by schema");
t.deepEqual(actual, expected, "results in multiple errors if multiple validators were specified");
}
function determinesWhetherSourceIsValid(t: tape.Test) {
const required = isRequired(() => "is required");
const schema: Schema = [["name", "name", [required]]];
const validator = policeman(schema);
t.is(validator({}).valid, false, "validator determines whether source is valid");
t.is(validator({ name: "foo" }).valid, true, "validator determines whether source is not valid");
function combinesMultipleValidators(t: Test) {
const requiredCheck = isRequired(() => "is required");
const emailCheck = isEmail(() => "is invalid email");
const validator = policeman([
["email", "email", combineValidators(requiredCheck, emailCheck)],
]);
const actual = validator({ email: "invalid" });
const expected = {
valid: false,
errors: {
email: "is invalid email",
},
};
t.deepEqual(actual, expected, "results in single error if multiple validators were combined");
}
function makeUseOfMapperFilter(t: tape.Test) {
function skipValidationByFilter(t: Test) {
interface User {
name: string;
age: number;
clubCard: string;
guest: boolean;
email?: string;
}
const required = isRequired(() => "is required");
const isUnderage: Filter = (_value, source) => (<User> source).age < 18;
const schema: Schema = [
["name", "name", [required]],
["clubCard", "clubCard", [required], isUnderage],
];
const validator = policeman(schema);
t.is(validator({ name: "Foo", age: 18 }).valid, true);
t.is(validator({ name: "Foo", age: 17 }).valid, false);
t.deepEqual((<User> validator({ name: "Foo", age: 17 }).errors).clubCard, ["is required"]);
t.is(validator({ name: "Foo", age: 17, clubCard: "123ABC" }).valid, true);
const requiredCheck = isRequired(() => "is required");
const emailCheck = isEmail(() => "is invalid email");
const isntGuest: Filter = (value: any, source: User) => source.guest !== true;
const validator = policeman([
["email", "email", [requiredCheck, emailCheck], isntGuest],
]);
const actual = validator({ guest: true });
const expected = {
valid: true,
errors: {},
};
t.deepEqual(actual, expected, "skips entry validation if filter gives false");
}
tape("policeman", (t: tape.Test) => {
t.plan(7);
returnsErrorObjects(t);
determinesWhetherSourceIsValid(t);
makeUseOfMapperFilter(t);
tape("policeman", (t: Test) => {
t.plan(4);
appliesSignleValidator(t);
appliesMultipleValidators(t);
combinesMultipleValidators(t);
skipValidationByFilter(t);
});
import * as tape from "tape";
import { EntryValidator } from "../lib/policeman";
import {
isRequired,
minLength,
maxLength,
isMinLength,
isMaxLength,
isEqualLength,
isEmail,
isMatching,
isPassing,
} from "../lib/validators";
} from "../lib/policeman";

@@ -17,20 +17,27 @@ function testIsRequired(t: tape.Test) {

t.is(required(undefined), "is required", "isRequired fails on undefined");
t.is(required(false), "is required", "isRequired fails on false");
t.is(required(false), null, "isRequired accepts false");
t.is(required("foo"), null, "isRequired accepts not empty strings");
}
function testMinLengthValidator(t: tape.Test) {
const minLength4: EntryValidator = minLength(4, () => "should be at least 4");
t.is(minLength4("foo bar"), null, "minLength(4) accepts strings with 4+ characters");
t.is(minLength4("fooz"), null, "minLength(4) accepts strings with 4 characters");
t.is(minLength4("foo"), "should be at least 4", "minLength(4) fails on strings with 4- characters");
function testIsMinLengthValidator(t: tape.Test) {
const isMinLength4 = isMinLength(4, () => "should be at least 4");
t.is(isMinLength4("foo bar"), null, "isMinLength(4) accepts strings with 4+ characters");
t.is(isMinLength4("fooz"), null, "isMinLength(4) accepts strings with 4 characters");
t.is(isMinLength4("foo"), "should be at least 4", "isMinLength(4) fails on strings with 4- characters");
}
function testMaxLengthValidator(t: tape.Test) {
const maxLength4: EntryValidator = maxLength(4, () => "should be at most 4");
t.is(maxLength4("foo bar"), "should be at most 4", "maxLength(4) fails on strings with 4+ characters");
t.is(maxLength4("fooz"), null, "maxLength(4) accepts strings with 4 characters");
t.is(maxLength4("foo"), null, "maxLength(4) accepts strings with 4- characters");
function testIsMaxLengthValidator(t: tape.Test) {
const isMaxLength4 = isMaxLength(4, () => "should be at most 4");
t.is(isMaxLength4("foo bar"), "should be at most 4", "isMaxLength(4) fails on strings with 4+ characters");
t.is(isMaxLength4("fooz"), null, "isMaxLength(4) accepts strings with 4 characters");
t.is(isMaxLength4("foo"), null, "isMaxLength(4) accepts strings with 4- characters");
}
function testIsEqualLengthValidator(t: tape.Test) {
const isEqualLength4 = isEqualLength(4, () => "should be 4 characters long");
t.is(isEqualLength4("abc"), "should be 4 characters long", "isEqualLength(4) fails on 3 characters long string");
t.is(isEqualLength4("abcde"), "should be 4 characters long", "isEqualLength(4) fails on 5 characters long string");
t.is(isEqualLength4("abcd"), null, "isEqualLength(4) accepts 4 characters long string");
}
function testIsEmail(t: tape.Test) {

@@ -57,6 +64,7 @@ const email = isEmail(() => "is invalid email");

tape("validators", (t: tape.Test) => {
t.plan(18);
t.plan(21);
testIsRequired(t);
testMinLengthValidator(t);
testMaxLengthValidator(t);
testIsMinLengthValidator(t);
testIsMaxLengthValidator(t);
testIsEqualLengthValidator(t);
testIsEmail(t);

@@ -63,0 +71,0 @@ testIsMatching(t);

"use strict";
var tape = require("tape");
var policeman_1 = require("../lib/policeman");
var validators_1 = require("../lib/validators");
function returnsErrorObjects(t) {
var required = validators_1.isRequired(function () { return "is required"; });
var minLength20 = validators_1.minLength(20)(function () { return "should contain at least 10 characters"; });
var schema = [
["firstName", "personal.first_name", [required]],
["lastName", "personal.last_name", [required]],
["other.bio", "bio", [required, minLength20]],
];
var validator = policeman_1.default(schema);
var source = {
personal: {
first_name: "Foo",
const tape = require("tape");
const policeman_1 = require("../lib/policeman");
const validators_1 = require("../lib/validators");
function appliesSignleValidator(t) {
const requiredCheck = validators_1.isRequired(() => "is required");
const validator = policeman_1.default([
["fullName", "full_name", requiredCheck],
]);
const actual = validator({});
const expected = {
valid: false,
errors: {
fullName: "is required",
},
bio: "Lorem ipsum",
};
var expected = {
firstName: [],
lastName: ["is required"],
other: {
bio: ["should contain at least 10 characters"],
t.deepEqual(actual, expected, "results in single error if single validator was specified");
}
function appliesMultipleValidators(t) {
const requiredCheck = validators_1.isRequired(() => "is required");
const emailCheck = validators_1.isEmail(() => "is invalid email");
const validator = policeman_1.default([
["email", "email", [requiredCheck, emailCheck]],
]);
const actual = validator({});
const expected = {
valid: false,
errors: {
email: ["is required", "is invalid email"],
},
};
var errors = validator(source).errors;
t.deepEqual(errors, expected, "validator returns errors object defined by schema");
t.deepEqual(actual, expected, "results in multiple errors if multiple validators were specified");
}
function determinesWhetherSourceIsValid(t) {
var required = validators_1.isRequired(function () { return "is required"; });
var schema = [["name", "name", [required]]];
var validator = policeman_1.default(schema);
t.is(validator({}).valid, false, "validator determines whether source is valid");
t.is(validator({ name: "foo" }).valid, true, "validator determines whether source is not valid");
function combinesMultipleValidators(t) {
const requiredCheck = validators_1.isRequired(() => "is required");
const emailCheck = validators_1.isEmail(() => "is invalid email");
const validator = policeman_1.default([
["email", "email", policeman_1.combineValidators(requiredCheck, emailCheck)],
]);
const actual = validator({ email: "invalid" });
const expected = {
valid: false,
errors: {
email: "is invalid email",
},
};
t.deepEqual(actual, expected, "results in single error if multiple validators were combined");
}
function makeUseOfMapperFilter(t) {
var required = validators_1.isRequired(function () { return "is required"; });
var isUnderage = function (_value, source) { return source.age < 18; };
var schema = [
["name", "name", [required]],
["clubCard", "clubCard", [required], isUnderage],
];
var validator = policeman_1.default(schema);
t.is(validator({ name: "Foo", age: 18 }).valid, true);
t.is(validator({ name: "Foo", age: 17 }).valid, false);
t.deepEqual(validator({ name: "Foo", age: 17 }).errors.clubCard, ["is required"]);
t.is(validator({ name: "Foo", age: 17, clubCard: "123ABC" }).valid, true);
function skipValidationByFilter(t) {
const requiredCheck = validators_1.isRequired(() => "is required");
const emailCheck = validators_1.isEmail(() => "is invalid email");
const isntGuest = (value, source) => source.guest !== true;
const validator = policeman_1.default([
["email", "email", [requiredCheck, emailCheck], isntGuest],
]);
const actual = validator({ guest: true });
const expected = {
valid: true,
errors: {},
};
t.deepEqual(actual, expected, "skips entry validation if filter gives false");
}
tape("policeman", function (t) {
t.plan(7);
returnsErrorObjects(t);
determinesWhetherSourceIsValid(t);
makeUseOfMapperFilter(t);
tape("policeman", (t) => {
t.plan(4);
appliesSignleValidator(t);
appliesMultipleValidators(t);
combinesMultipleValidators(t);
skipValidationByFilter(t);
});
//# sourceMappingURL=policeman.test.js.map
"use strict";
var tape = require("tape");
var validators_1 = require("../lib/validators");
const tape = require("tape");
const policeman_1 = require("../lib/policeman");
function testIsRequired(t) {
var required = validators_1.isRequired(function () { return "is required"; });
const required = policeman_1.isRequired(() => "is required");
t.is(required(""), "is required", "isRequired fails on empty string");
t.is(required(null), "is required", "isRequired fails on null");
t.is(required(undefined), "is required", "isRequired fails on undefined");
t.is(required(false), "is required", "isRequired fails on false");
t.is(required(false), null, "isRequired accepts false");
t.is(required("foo"), null, "isRequired accepts not empty strings");
}
function testMinLengthValidator(t) {
var minLength4 = validators_1.minLength(4, function () { return "should be at least 4"; });
t.is(minLength4("foo bar"), null, "minLength(4) accepts strings with 4+ characters");
t.is(minLength4("fooz"), null, "minLength(4) accepts strings with 4 characters");
t.is(minLength4("foo"), "should be at least 4", "minLength(4) fails on strings with 4- characters");
function testIsMinLengthValidator(t) {
const isMinLength4 = policeman_1.isMinLength(4, () => "should be at least 4");
t.is(isMinLength4("foo bar"), null, "isMinLength(4) accepts strings with 4+ characters");
t.is(isMinLength4("fooz"), null, "isMinLength(4) accepts strings with 4 characters");
t.is(isMinLength4("foo"), "should be at least 4", "isMinLength(4) fails on strings with 4- characters");
}
function testMaxLengthValidator(t) {
var maxLength4 = validators_1.maxLength(4, function () { return "should be at most 4"; });
t.is(maxLength4("foo bar"), "should be at most 4", "maxLength(4) fails on strings with 4+ characters");
t.is(maxLength4("fooz"), null, "maxLength(4) accepts strings with 4 characters");
t.is(maxLength4("foo"), null, "maxLength(4) accepts strings with 4- characters");
function testIsMaxLengthValidator(t) {
const isMaxLength4 = policeman_1.isMaxLength(4, () => "should be at most 4");
t.is(isMaxLength4("foo bar"), "should be at most 4", "isMaxLength(4) fails on strings with 4+ characters");
t.is(isMaxLength4("fooz"), null, "isMaxLength(4) accepts strings with 4 characters");
t.is(isMaxLength4("foo"), null, "isMaxLength(4) accepts strings with 4- characters");
}
function testIsEqualLengthValidator(t) {
const isEqualLength4 = policeman_1.isEqualLength(4, () => "should be 4 characters long");
t.is(isEqualLength4("abc"), "should be 4 characters long", "isEqualLength(4) fails on 3 characters long string");
t.is(isEqualLength4("abcde"), "should be 4 characters long", "isEqualLength(4) fails on 5 characters long string");
t.is(isEqualLength4("abcd"), null, "isEqualLength(4) accepts 4 characters long string");
}
function testIsEmail(t) {
var email = validators_1.isEmail(function () { return "is invalid email"; });
const email = policeman_1.isEmail(() => "is invalid email");
t.is(email("foo@bar.com"), null, "isEmail accepts valid email");

@@ -30,3 +36,3 @@ t.is(email("foo@.com"), "is invalid email", "isEmail fails on invalid email");

function testIsMatching(t) {
var matching = validators_1.isMatching(/^\d{3}-?\d{3}-?\d{3}$/, function () { return "is invalid number"; });
const matching = policeman_1.isMatching(/^\d{3}-?\d{3}-?\d{3}$/, () => "is invalid number");
t.is(matching("777-888-999"), null, "isMatching(/^\d{3}-?\d{3}-?\d{3}$/) accepts valid number");

@@ -37,12 +43,13 @@ t.is(matching("777888999"), null, "isMatching(/^\d{3}-?\d{3}-?\d{3}$/) accepts valid number");

function testIsPassing(t) {
var isFoo = function (str) { return str === "foo"; };
var matching = validators_1.isPassing(isFoo, function () { return "must be \"foo\""; });
const isFoo = (str) => str === "foo";
const matching = policeman_1.isPassing(isFoo, () => "must be \"foo\"");
t.is(matching("foo"), null, "predicate returns true on \"foo\"");
t.is(matching("bar"), "must be \"foo\"", "predicate returns false on not \"foo\"");
}
tape("validators", function (t) {
t.plan(18);
tape("validators", (t) => {
t.plan(21);
testIsRequired(t);
testMinLengthValidator(t);
testMaxLengthValidator(t);
testIsMinLengthValidator(t);
testIsMaxLengthValidator(t);
testIsEqualLengthValidator(t);
testIsEmail(t);

@@ -49,0 +56,0 @@ testIsMatching(t);

{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"target": "es6",
"noImplicitAny": true,

@@ -6,0 +6,0 @@ "sourceMap": true,

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc