onsubmit
Version:
Simple validation utilities in typescript.
234 lines (227 loc) • 7.78 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
validateField: () => validateField,
validateForm: () => validateForm
});
module.exports = __toCommonJS(src_exports);
// src/internal/error-management.ts
var MappingError = class extends Error {
constructor(message = "Mapping Error", name = "MAPPING_ERROR") {
super();
this.name = name;
this.message = message;
}
};
var CustomTypeError = class extends TypeError {
constructor(message = "Type Error", name = "TYPE_ERROR") {
super();
this.name = name;
this.message = `Bad arguments: ${message}`;
}
};
var RequiredParamError = class extends TypeError {
constructor(message = "Required Param Error", name = "REQUIRED_PARAM_ERROR") {
super();
this.name = name;
this.message = `Required param: ${message}`;
}
};
function handleError(error) {
if (error.name === "TYPE_ERROR") {
console.error(error.message);
} else if (error.name === "REQUIRED_PARAM_ERROR") {
console.error(error.message);
} else if (error.name === "MAPPING_ERROR") {
console.error(error.message);
} else {
console.error(
"Internal Error",
error.message,
"Please report this athttps://github.com/AmmarHalees/onsubmit/issues"
);
}
}
// src/utils/index.ts
var isDateObject = (value) => value instanceof Date && !isNaN(value.getTime());
var isString = (value) => typeof value === "string" || value instanceof String;
var isNumber = (value) => typeof value === "number" && isFinite(value);
var isNullOrUndefined = (value) => value == null;
var isBoolean = (value) => typeof value === "boolean";
var isObjectType = (value) => typeof value === "object";
var isFunction = (value) => typeof value === "function";
var isObject = (value) => !isNullOrUndefined(value) && !Array.isArray(value) && isObjectType(value) && !isDateObject(value);
var isRegExp = (value) => value instanceof RegExp;
var isFile = (element) => element.type === "file";
var utils = {
isDateObject,
isString,
isNumber,
isNullOrUndefined,
isObject,
isFile,
isBoolean,
isFunction,
isRegExp
};
var utils_default = utils;
// src/core/validateField.ts
function validateField(value, name, rulesObject) {
const errors = [];
try {
let isKeyOfConfigMap2 = function(key) {
return key in configMap;
};
var isKeyOfConfigMap = isKeyOfConfigMap2;
if (!utils_default.isString(value))
throw new CustomTypeError("'value' must be a string");
if (!utils_default.isString(name))
throw new CustomTypeError("'name' must be a string");
const configMap = {
minLength: (value2, criterion, message) => {
if (!utils_default.isNumber(criterion))
throw new CustomTypeError("'criterion' must be a number");
if (!utils_default.isString(message))
throw new CustomTypeError("'message' must be a string");
if (value2 && value2.length > 0 && !(value2.length >= criterion)) {
errors.push({ name, message });
}
},
maxLength: (value2, criterion, message) => {
if (!utils_default.isNumber(criterion))
throw new CustomTypeError("'criterion' must be a number");
if (!utils_default.isString(message))
throw new CustomTypeError("'message' must be a string");
if (value2 && !(value2.length <= criterion)) {
errors.push({ name, message });
}
},
pattern: (value2, criterion, message) => {
if (!utils_default.isRegExp(criterion))
throw new CustomTypeError("'criterion' must be a RegExp");
if (!utils_default.isString(message))
throw new CustomTypeError("'message' must be a string");
if (value2.length > 0 && !value2.match(criterion)) {
errors.push({ name, message });
}
},
custom: (value2, criterion, message) => {
if (!utils_default.isFunction(criterion))
throw new CustomTypeError("'criterion' must be a function");
if (!utils_default.isString(message))
throw new CustomTypeError("'message' must be a string");
if (criterion(value2)) {
errors.push({ name, message });
}
},
required: (value2, criterion, message) => {
if (!utils_default.isBoolean(criterion))
throw new CustomTypeError("'criterion' must be a boolean");
if (!utils_default.isString(message))
throw new CustomTypeError("'message' must be a string");
if (value2.replace(/\s/g, "") === "" && criterion) {
errors.push({ name, message });
}
}
};
Object.entries(rulesObject).forEach(([key, { criterion, message }]) => {
if (isKeyOfConfigMap2(key)) {
const validationFunction = configMap[key];
if (validationFunction) {
validationFunction(value, criterion, message);
} else {
throw new MappingError(
`No validation function found for ${key} in configMap`
);
}
}
});
} catch (error) {
if (error instanceof Error) {
handleError(error);
} else {
console.log(error);
}
}
return errors;
}
// src/internal/do-keys-match.ts
function doKeysMatch(data, NameRuleMap) {
const dataKeys = Object.keys(data);
const NameRuleMapKeys = Object.keys(NameRuleMap);
if (dataKeys.length !== NameRuleMapKeys.length) {
throw new MappingError(
`Data keys and NameRuleMap keys do not match. Data keys: ${dataKeys}, NameRuleMap keys: ${NameRuleMapKeys}`
);
}
dataKeys.forEach((key) => {
if (!NameRuleMapKeys.includes(key)) {
throw new MappingError(
`Data keys and NameRuleMap keys do not match. Data keys: ${dataKeys}, NameRuleMap keys: ${NameRuleMapKeys}`
);
}
});
}
// src/core/validateForm.ts
function validateForm(data, NameRuleMap) {
const errors = [];
try {
if (!NameRuleMap)
throw new RequiredParamError("NameRuleMap is required");
if (!data)
throw new RequiredParamError("data is required");
if (!utils_default.isObject(data))
throw new CustomTypeError(`Form Data cannot be ${typeof data}`);
if (!utils_default.isObject(NameRuleMap)) {
throw new CustomTypeError(`NameRuleMap cannot be ${typeof NameRuleMap}`);
}
doKeysMatch(data, NameRuleMap);
Object.entries(data).forEach(([key, value]) => {
let stringVal = "";
if (typeof value === "string") {
stringVal = value;
} else if (value instanceof FormData) {
stringVal = value.get(key);
}
if (NameRuleMap) {
errors.push(
...validateField(
stringVal,
key,
NameRuleMap[key]
)
);
}
});
} catch (error) {
if (error instanceof Error) {
handleError(error);
} else {
console.log(error);
}
}
return errors;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
validateField,
validateForm
});