decoval
Version:
DecoVal is a decorator-driven validation pattern that allows you to add validation rules directly to the properties of TypeScript classes, simplifying data control and increasing code readability and reusability.
26 lines (25 loc) • 1.17 kB
JavaScript
import { ValidationError } from "./error/validation.error";
import { registerValidation } from "./register.validation";
import { skipValidation } from "./skip/skip.validation";
export function DvURL(options) {
return function (target, propertyKey) {
const customMessage = (options === null || options === void 0 ? void 0 : options.message) || `The "${propertyKey}" field must be a valid URL`;
const urlRegex = /^(https?:\/\/)?([\w\d\-]+\.)+[a-z]{2,6}(:\d+)?(\/[\w\d\-._~:/?#[\]@!$&'()*+,;%=]*)?$/i;
registerValidation(target, propertyKey, (value) => {
var _a;
const skipOpts = {
optional: true,
null: (_a = options === null || options === void 0 ? void 0 : options.allowNull) !== null && _a !== void 0 ? _a : true,
empty: true,
};
if (skipValidation(value, skipOpts))
return;
if (typeof value !== "string") {
throw new ValidationError(customMessage);
}
if (!urlRegex.test(value)) {
throw new ValidationError(customMessage);
}
});
};
}