New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

abolish

Package Overview
Dependencies
Maintainers
1
Versions
148
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

abolish - npm Package Compare versions

Comparing version 3.1.3 to 3.2.0

4

index.d.ts
import Abolish = require("./src/Abolish");
import { Rule } from "./src/Functions";
export { Abolish, Rule };
import { Rule, ParseRules } from "./src/Functions";
export { Abolish, Rule, ParseRules };
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Rule = exports.Abolish = void 0;
exports.ParseRules = exports.Rule = exports.Abolish = void 0;
const Abolish = require("./src/Abolish");

@@ -8,1 +8,2 @@ exports.Abolish = Abolish;

Object.defineProperty(exports, "Rule", { enumerable: true, get: function () { return Functions_1.Rule; } });
Object.defineProperty(exports, "ParseRules", { enumerable: true, get: function () { return Functions_1.ParseRules; } });
{
"name": "abolish",
"version": "3.1.3",
"version": "3.2.0",
"description": "A javascript object validator.",

@@ -25,4 +25,5 @@ "main": "index.js",

"@types/lodash.unset": "^4.5.6",
"@types/node": "^14.14.31",
"@types/node": "^14.14.37",
"axios": "^0.21.1",
"prettier": "^2.2.1",
"ts-node-dev": "^1.1.6",

@@ -29,0 +30,0 @@ "typescript": "^4.2.3"

# Abolish
A Javascript object validator for custom validations
Using the idea of [object-validator-pro](https://github.com/trapcodeio/object-validator-pro) but modern codes and typescript.
Using the idea of [object-validator-pro](https://github.com/trapcodeio/object-validator-pro) but modern codes and
typescript.

@@ -9,6 +11,9 @@ For direct browser Installation see [abolish-browser](https://www.npmjs.com/package/abolish-browser)

### Using Package Managers
```sh
npm install abolish
```
Using Yarn
```sh

@@ -19,23 +24,23 @@ yarn add abolish

### Basic Example
```javascript
const {Abolish} = require('abolish');
const aboy = new Abolish();
const abolish = new Abolish();
aboy.addValidator({
name: 'isEmail',
validator: (str) => {
return str.includes('@')
},
});
// Use abolish email validator
const EmailValidator = require('abolish/validators/string/email');
abolish.addValidator(EmailValidator);
aboy.addValidator({
name: 'addProtocol',
validator: (url, option, {modifier}) => {
if (url.substr(0, option.length) !== option) {
// add protocol
modifier.setThis(`${option}://${url}`)
}
return true
// Add Custom Validtor
abolish.addValidator({
name: 'addProtocol',
validator: (url, option, {modifier}) => {
// Check if url does not have required protocol
if (url.substr(0, option.length) !== option) {
// Add protocol
modifier.setThis(`${option}://${url}`)
}
return true
}
});

@@ -45,14 +50,14 @@

const form = {
email: 'appdeveloper@sky.com',
username: 'john_doe',
age: 18,
url: 'wildstream.ng'
email: 'appdeveloper@sky.com',
username: 'john_doe',
age: 18,
url: 'wildstream.ng'
};
const [error, validated] = aboy.validate(form, {
'*': 'must|typeOf:string',
email: 'isEmail',
username: '*',
age: 'typeOf:number|max:20',
url: 'addProtocol:http'
const [error, validated] = abolish.validate(form, {
$: 'required|typeOf:string', // $ or '*' is considered as wildcard
email: 'isEmail',
username: '*',
age: 'typeOf:number|max:20',
url: 'addProtocol:http'
});

@@ -64,2 +69,3 @@

#### Result
```

@@ -66,0 +72,0 @@ {

@@ -107,3 +107,3 @@ "use strict";

static validate(object, rules) {
return (new this).validate(object, rules);
return new this().validate(object, rules);
}

@@ -119,3 +119,3 @@ /**

static validateAsync(object, rules) {
return (new this).validateAsync(object, rules);
return new this().validateAsync(object, rules);
}

@@ -136,8 +136,9 @@ /**

/**
* Check for wildcard rules (*, **)
* Check for wildcard rules (*, $)
*/
let internalWildcardRules = {};
if (rules.hasOwnProperty('*')) {
internalWildcardRules = rules['*'];
delete rules['*'];
if (rules.hasOwnProperty("*") || rules.hasOwnProperty("$")) {
internalWildcardRules = rules["*"] || rules["$"];
delete rules["*"];
delete rules["$"];
/**

@@ -164,3 +165,3 @@ * Convert rules[*] to object if string

*/
if (ruleData === '*')
if (["*", "$"].includes(ruleData))
ruleData = {};

@@ -181,9 +182,9 @@ /**

let $skip = false;
if (ruleData.hasOwnProperty('$skip')) {
$skip = ruleData['$skip'];
delete ruleData['$skip'];
if (typeof $skip === 'function') {
if (ruleData.hasOwnProperty("$skip")) {
$skip = ruleData["$skip"];
delete ruleData["$skip"];
if (typeof $skip === "function") {
$skip = $skip(validated[rule]);
}
if (typeof $skip !== 'boolean') {
if (typeof $skip !== "boolean") {
throw new Error(`$skip value or resolved function value must be a BOOLEAN in RuleFor: (${rule})`);

@@ -200,6 +201,6 @@ }

let $name = false;
if (ruleData.hasOwnProperty('$name')) {
$name = ruleData['$name'];
delete ruleData['$name'];
if (typeof $name !== 'string') {
if (ruleData.hasOwnProperty("$name")) {
$name = ruleData["$name"];
delete ruleData["$name"];
if (typeof $name !== "string") {
throw new Error(`$skip value or resolved function value must be a BOOLEAN in RuleFor: (${rule})`);

@@ -212,6 +213,6 @@ }

let $error = false;
if (ruleData.hasOwnProperty('$error')) {
$error = ruleData['$error'];
delete ruleData['$error'];
if (!$error || typeof $error !== 'string') {
if (ruleData.hasOwnProperty("$error")) {
$error = ruleData["$error"];
delete ruleData["$error"];
if (!$error || typeof $error !== "string") {
throw new Error(`$error value must be a STRING in RuleFor: (${rule})`);

@@ -231,3 +232,4 @@ }

*/
if (!this.validators.hasOwnProperty(validatorName) && !GlobalValidators_1.default.hasOwnProperty(validatorName)) {
if (!this.validators.hasOwnProperty(validatorName) &&
!GlobalValidators_1.default.hasOwnProperty(validatorName)) {
throw new Error(`Validator: {${validatorName}} does not exists but defined in rules`);

@@ -238,3 +240,4 @@ }

*/
const validator = (this.validators[validatorName] || GlobalValidators_1.default[validatorName]);
const validator = (this.validators[validatorName] ||
GlobalValidators_1.default[validatorName]);
if (!isAsync && validator.isAsync) {

@@ -257,3 +260,10 @@ throw new Error(`Validator: {${validatorName}} is async, use validateAsync method instead.`);

if (isAsync) {
asyncData.jobs.push({ $name, rule, validator, validatorName, validatorOption, $error });
asyncData.jobs.push({
$name,
rule,
validator,
validatorName,
validatorOption,
$error
});
}

@@ -283,3 +293,3 @@ else {

key: rule,
type: 'internal',
type: "internal",
validator: validatorName,

@@ -296,3 +306,3 @@ message: e.message,

key: rule,
type: 'validator',
type: "validator",
validator: validatorName,

@@ -313,5 +323,5 @@ message: $error ? $error : validationResult.message,

*/
const optionIsStringable = typeof validatorOption === "string"
|| typeof validatorOption === "number"
|| Array.isArray(validatorOption);
const optionIsStringable = typeof validatorOption === "string" ||
typeof validatorOption === "number" ||
Array.isArray(validatorOption);
/**

@@ -321,5 +331,5 @@ * Replace :param with rule converted to upperCase

*/
let message = ($error ? $error : validator.error).replace(':param', $name ? $name : Functions_1.StartCase(rule, this));
let message = ($error ? $error : validator.error).replace(":param", $name ? $name : Functions_1.StartCase(rule, this));
if (optionIsStringable)
message = message.replace(':option', validatorOption);
message = message.replace(":option", validatorOption);
// Return Error using the ValidationResult format

@@ -329,3 +339,3 @@ return [

key: rule,
type: 'validator',
type: "validator",
validator: validatorName,

@@ -348,6 +358,3 @@ message,

validated = Functions_1.Pick(validated, keysToBeValidated);
return [
false,
validated
];
return [false, validated];
}

@@ -404,18 +411,24 @@ /**

*/
return resolve([{
return resolve([
{
key: rule,
type: 'internal',
type: "internal",
validator: validatorName,
message: e.message,
data: e.stack
}, {}]);
},
{}
]);
}
if (validationResult instanceof AbolishError_1.default) {
return resolve([{
return resolve([
{
key: rule,
type: 'validator',
type: "validator",
validator: validatorName,
message: $error ? $error : validationResult.message,
data: validationResult.data
}, {}]);
},
{}
]);
}

@@ -435,13 +448,16 @@ else if (validationResult === false) {

*/
let message = ($error ? $error : validator.error).replace(':param', $name ? $name : Functions_1.StartCase(rule, this));
let message = ($error ? $error : validator.error).replace(":param", $name ? $name : Functions_1.StartCase(rule, this));
if (optionIsStringable)
message = message.replace(':option', validatorOption);
message = message.replace(":option", validatorOption);
// Return Error using the ValidationResult format
return resolve([{
return resolve([
{
key: rule,
type: 'validator',
type: "validator",
validator: validatorName,
message,
data: null
}, {}]);
},
{}
]);
}

@@ -448,0 +464,0 @@ }

@@ -25,3 +25,7 @@ "use strict";

function StartCase(str, abolishInstance) {
return abolishInstance ? (abolishInstance.config.useStartCaseInErrors ? lodash_startcase_1.default(str) : str) : lodash_startcase_1.default(str);
return abolishInstance
? abolishInstance.config.useStartCaseInErrors
? lodash_startcase_1.default(str)
: str
: lodash_startcase_1.default(str);
}

@@ -79,10 +83,11 @@ exports.StartCase = StartCase;

path = path.toString().match(/[^.[\]]+/g) || [];
path.slice(0, -1).reduce((a, c, i) => // Iterate all of them except the last one
Object(a[c]) === a[c] // Does the key exist and is its value an object?
// Yes: then follow that path
? a[c]
// No: create the key. Is the next key a potential array-index?
: a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1]
? [] // Yes: assign a new array object
: {}, // No: assign a new plain object
path.slice(0, -1).reduce((a, c, i // Iterate all of them except the last one
) => Object(a[c]) === a[c] // Does the key exist and is its value an object?
? // Yes: then follow that path
a[c]
: // No: create the key. Is the next key a potential array-index?
(a[c] =
Math.abs(path[i + 1]) >> 0 === +path[i + 1]
? [] // Yes: assign a new array object
: {}), // No: assign a new plain object
object)[path[path.length - 1]] = value; // Finally assign the value to the last key

@@ -93,3 +98,3 @@ return object; // Return the top-level object to allow chaining

function Get(obj, path, defaultValue) {
if (path.indexOf('.') >= 0) {
if (path.indexOf(".") >= 0) {
const travel = (regexp) => String.prototype.split

@@ -96,0 +101,0 @@ .call(path, regexp)

"use strict";
function trimIfString(value) {
return typeof value === 'string' ? value.trim() : value;
return typeof value === "string" ? value.trim() : value;
}
const GlobalValidators = {
must: {
name: 'must',
error: ':param is required.',
name: "must",
error: ":param is required.",
validator: (value, option) => {

@@ -16,11 +16,11 @@ if (!option) {

}
else if (typeof value === 'string' || Array.isArray(value)) {
else if (typeof value === "string" || Array.isArray(value)) {
return value.length > 0;
}
return true;
},
}
},
typeof: {
name: 'typeof',
error: ':param is not typeOf :option',
name: "typeof",
error: ":param is not typeOf :option",
validator: (value, option) => {

@@ -33,3 +33,3 @@ /**

option = option.toLowerCase();
if (option === 'array')
if (option === "array")
return Array.isArray(value);

@@ -40,11 +40,11 @@ return typeof value === option;

exact: {
name: 'exact',
name: "exact",
validator: (value, option) => {
return value === option;
},
error: ':param failed exact validator'
error: ":param failed exact validator"
},
min: {
name: 'min',
error: ':param is too small. (Min. :option)',
name: "min",
error: ":param is too small. (Min. :option)",
validator: (value, option, helpers) => {

@@ -67,4 +67,4 @@ const isNotNumber = isNaN(value);

max: {
name: 'max',
error: ':param is too big. (Max. :option)',
name: "max",
error: ":param is too big. (Max. :option)",
validator: (value, option, helpers) => {

@@ -87,6 +87,6 @@ const isNotNumber = isNaN(value);

minLength: {
name: 'minLength',
error: ':param is too short. (Min. :option characters)',
name: "minLength",
error: ":param is too short. (Min. :option characters)",
validator: (value, option) => {
if (typeof value !== 'string' && !Array.isArray(value))
if (typeof value !== "string" && !Array.isArray(value))
return false;

@@ -98,6 +98,6 @@ value = trimIfString(value);

maxLength: {
name: 'maxLength',
error: ':param is too long. (Max. :option characters)',
name: "maxLength",
error: ":param is too long. (Max. :option characters)",
validator: (value, option) => {
if (typeof value !== 'string' && !Array.isArray(value))
if (typeof value !== "string" && !Array.isArray(value))
return false;

@@ -109,4 +109,4 @@ value = trimIfString(value);

selectMin: {
name: 'selectMin',
error: 'Select at-least :option :param.',
name: "selectMin",
error: "Select at-least :option :param.",
validator: (value, option, helpers) => {

@@ -117,4 +117,4 @@ return GlobalValidators.minLength.validator(value, option, helpers);

selectMax: {
name: 'selectMax',
error: 'Select at-most :option :param.',
name: "selectMax",
error: "Select at-most :option :param.",
validator: (value, option, helpers) => {

@@ -125,4 +125,4 @@ return GlobalValidators.maxLength.validator(value, option, helpers);

$inline: {
name: '$inline',
error: ':param failed inline validation.',
name: "$inline",
error: ":param failed inline validation.",
validator: (v, o, helpers) => {

@@ -137,3 +137,3 @@ return o(v, helpers);

GlobalValidators.required = Object.assign({}, GlobalValidators.must);
GlobalValidators.required.name = 'required';
GlobalValidators.required.name = "required";
module.exports = GlobalValidators;

@@ -35,9 +35,11 @@ "use strict";

const StringToRules = (str) => {
let s = str.split('|');
let s = str.split("|");
const keyColumnValObj = {};
for (let i = 0; i < s.length; i++) {
const pair = s[i];
if (pair.match(keyColumnValStringSingleQuotes) || pair.match(keyColumnValStringDoubleQuotes) || pair.match(keyColumnValStringGraveAccent)) {
if (pair.match(keyColumnValStringSingleQuotes) ||
pair.match(keyColumnValStringDoubleQuotes) ||
pair.match(keyColumnValStringGraveAccent)) {
const [key, ...value] = pair.split(":");
let valueToString = value.join(':');
let valueToString = value.join(":");
valueToString = valueToString.substr(1);

@@ -62,3 +64,3 @@ valueToString = valueToString.substr(0, value.length - 1);

// if !key set value to false
if (key.substr(0, 1) === '!') {
if (key.substr(0, 1) === "!") {
key = key.substr(1);

@@ -65,0 +67,0 @@ value = false;

@@ -10,3 +10,3 @@ import AbolishError from "./AbolishError";

key: string;
type: 'internal' | 'validator';
type: "internal" | "validator";
message: string;

@@ -21,6 +21,3 @@ validator: string;

*/
export declare type ValidationResult<T = any> = [
error: ValidationError | false,
validated: T
];
export declare type ValidationResult<T = any> = [error: ValidationError | false, validated: T];
export declare type AbolishValidatorFunction = (value: any, option: any, helpers: {

@@ -27,0 +24,0 @@ error: (message: string, data?: any) => AbolishError;

"use strict";
module.exports = {
name: 'any',
name: "any",
validator: (v, o) => {

@@ -5,0 +5,0 @@ return o.includes(v);

"use strict";
module.exports = {
name: 'alphaNumeric',
error: ':param allows only AlphaNumeric characters.',
validator: (str) => (new RegExp(/^[a-z0-9]+$/i)).test(str)
name: "alphaNumeric",
error: ":param allows only AlphaNumeric characters.",
validator: (str) => new RegExp(/^[a-z0-9]+$/i).test(str)
};
"use strict";
module.exports = {
name: 'boolean',
error: ':param is not a boolean',
name: "boolean",
error: ":param is not a boolean",
/**

@@ -17,7 +17,7 @@ * @param str

str = str.toLowerCase();
if (str === 'true') {
if (str === "true") {
modifier.setThis(true);
return true;
}
else if (str === 'false') {
else if (str === "false") {
modifier.setThis(false);

@@ -24,0 +24,0 @@ return true;

"use strict";
module.exports = {
name: 'date',
name: "date",
validator: (v, o, { modifier }) => {

@@ -5,0 +5,0 @@ if (v instanceof Date) {

"use strict";
module.exports = {
name: 'email',
error: ':param is not a valid email.',
name: "email",
error: ":param is not a valid email.",
validator: (email) => {

@@ -6,0 +6,0 @@ return /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(email);

"use strict";
module.exports = {
name: 'ipAddress',
error: ':param is not a valid IP address.',
name: "ipAddress",
error: ":param is not a valid IP address.",
validator: (ip) => {

@@ -6,0 +6,0 @@ const isIpRegex = new RegExp(/((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))/gm);

"use strict";
module.exports = {
name: 'json',
error: ':param is not a valid JSON string',
name: "json",
error: ":param is not a valid JSON string",
validator: (str) => {

@@ -6,0 +6,0 @@ if (typeof str !== "string")

"use strict";
module.exports = {
name: 'jsonDecode',
error: ':param is not a valid JSON string',
name: "jsonDecode",
error: ":param is not a valid JSON string",
/**

@@ -6,0 +6,0 @@ * @param str

"use strict";
module.exports = {
name: 'number',
error: ':param is not a valid number',
name: "number",
error: ":param is not a valid number",
/**

@@ -6,0 +6,0 @@ *

"use strict";
module.exports = {
name: 'regex',
error: ':param failed Regex test.',
name: "regex",
error: ":param failed Regex test.",
validator: (str, regex) => {

@@ -6,0 +6,0 @@ const isRegex = regex instanceof RegExp;

"use strict";
module.exports = {
name: 'url',
error: ':param is not a valid URL',
name: "url",
error: ":param is not a valid URL",
validator: (str) => {
const pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
const pattern = new RegExp("^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$", "i"); // fragment locator
return pattern.test(str);
}
};
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