{"id":26581669,"url":"https://github.com/besworks/validatedmethod","last_synced_at":"2026-04-20T10:02:50.438Z","repository":{"id":281748926,"uuid":"946265530","full_name":"besworks/ValidatedMethod","owner":"besworks","description":"Provides runtime type checking for JavaScript function parameters similar to TypeScript, but with no compiling or dependencies. ","archived":false,"fork":false,"pushed_at":"2025-05-16T18:40:30.000Z","size":67,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-11T04:31:48.798Z","etag":null,"topics":["javascript","js","library","npm-package","typesafety","typescript","validation"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/besworks.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-03-10T21:49:25.000Z","updated_at":"2025-05-16T18:40:34.000Z","dependencies_parsed_at":null,"dependency_job_id":"db29a767-6bda-41cf-83ac-a08b5290a752","html_url":"https://github.com/besworks/ValidatedMethod","commit_stats":null,"previous_names":["besworks/validatedmethod"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/besworks/ValidatedMethod","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/besworks%2FValidatedMethod","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/besworks%2FValidatedMethod/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/besworks%2FValidatedMethod/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/besworks%2FValidatedMethod/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/besworks","download_url":"https://codeload.github.com/besworks/ValidatedMethod/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/besworks%2FValidatedMethod/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32042293,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-20T00:18:06.643Z","status":"online","status_checked_at":"2026-04-20T02:00:06.527Z","response_time":94,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","js","library","npm-package","typesafety","typescript","validation"],"created_at":"2025-03-23T07:31:09.806Z","updated_at":"2026-04-20T10:02:50.431Z","avatar_url":"https://github.com/besworks.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![npm version](https://img.shields.io/npm/v/validated-method)](https://www.npmjs.com/package/validated-method)\n\n# ValidatedMethod\nProvides runtime type checking for JavaScript function parameters similar to TypeScript, but with no compiling or dependencies. \n\n## Features\n- Zero dependencies\n- TypeScript-like parameter validation in pure JavaScript\n- Named, single, and positional parameter support\n- Coercion options for numbers and booleans\n- Regular Expression validation for strings\n- Custom type support\n- Extra parameter warnings\n- Optional return type validation\n- Easy to integrate with intuitive syntax\n- Supports async / Promsie chaining\n- Full test suite included\n\n## Installation\n\nInstall via npm.\n\n```sh\nnpm i validated-method\n```\n\nOr import from CDN.\n\n```js\nimport { ValidatedMethod } from 'https://unpkg.com/validated-method/validated-method.js';\n```\n\nOr copy `validated-method.js` into your project.\n\n## Usage\n\n```javascript\nimport { ValidatedMethod } from 'validated-method';\n\nclass UserService {\n    createUser = new ValidatedMethod({\n        username: 'string',\n        age: 'number',\n        active: 'boolean',\n        roles: 'array',\n        settings: 'object',\n        email: /^[^@]+@[^@]+\\.[^@]+$/,\n        birthday: ['string', 'optional']\n        title: 'string'\n    }, async opts =\u003e {\n        // Parameters are validated, safe to use\n        return await db.users.create(opts);\n    });\n}\n\nconst myService = new UserService();\n\nmyService.createUser({\n    username: 'besworks',\n    age: 40,\n    active: true,\n    roles: [ 'admin', 'wizard' ],\n    settings: { darkmode: 'auto' },\n    email: 'example@domain.tld',\n    // birthday: is optional so undefined is ok\n    // Throw TypeError because title: is undefined\n});\n\n```\n\n## Type Validation\n\n### Basic Types\n- `'string'` - String values\n- `'boolean'` - Truthy/Falsey values (coerced using `Boolean()`)\n- `'object'` - Object literals\n- `'array'` - Arrays of any length including 0\n- `'function'` - Executable functions\n- `'null'` - Empty values\n\n### Number Types\n- `'int'` - Integers with truncating coercion (uses `parseInt()`)\n- `'roundint'` - Integers with rounding coercion (uses `Math.round()`)\n- `'strictint'` - Integers without coercion\n- `'number'` - Alias of `'float'`\n- `'float'` - Floating point numbers with coercion (uses `parseFloat()`)\n- `'strictfloat'` - Floating point numbers without coercion\n\n### Special Types\n- `'any'` - Any value including `null`, except `undefined`\n- `'undefined'` - Alias of `'optional'`\n- `'optional'` - Value can be `undefined`\n- `'strictboolean'` - Booleans only without coercion\n- `/^test$/ig` - Regular Expression literal (without quotes, uses `toString()`)\n- `ClassName` - Class comparison (using `instanceof`)\n- `(a) =\u003e a === b` - any declared or incline function can be used as a validator\n\n### Import Alias\n\nThe `_$` helper is provided for convenience but can be renamed on import if it conflicts with other libraries:\n\n```javascript\nimport { _$ as VM } from 'validated-method';\nconst getData = VM('string', performLookupByName);\n```\n\n### Custom Types\n```javascript\nclass Widget {\n    node = document.getElementById('widget')\n        ?? document.createElement('custom-widget');\n}\n\nconst configureWidget = _$({\n    widget: Widget,\n    className: 'string'\n}, opts =\u003e {\n    opts.widget.node.classList.add(opts.className);\n    // safe to call classList because we know\n    // opts.widget.node is an HTMLElement\n    // and opts.className is a string\n});\n\nconfigureWidget(new Widget(), 'green');\n```\n\n## Extra Parameter Warnings\n\nBy default, ValidatedMethod warns about unexpected parameters:\n\n```javascript\nconst addRecord = _$({\n    name: 'string',\n    age: 'number'\n}, insertData);\n\naddRecord({\n    name: 'test',\n    age: 40,\n    extra: true  // Warning: \"Unexpected parameter: extra\"\n});\n```\n\n### Quiet Mode\n\nYou can globally supress warnings with the static `quiet` flag.\n\n```javascript\nValidatedMethod.quiet = true;\n\nconst getData = _$({\n    bleep: 'boolean',\n    bloop: 'array'\n}, opts =\u003e {\n    return {\n        e: opts.bleep,\n        o: opts.bloop\n    }\n});\n\nconst ref = {\n    bleep: true,\n    bloop: [],\n    derp: { ...bigObj },\n    zzz: 'more'\n};\n\ngetData(ref); // no warnings, best for production\n```\n\n## Parameter Styles\n\n### Named Parameters\n```javascript\nconst method = _$(\n    { name: 'string', age: 'number' },\n    opts =\u003e `${opts.name} is ${opts.age}`\n);\n\nmethod({ name: 'Test', age: 42 });\n```\n\n### Single Parameter\n```javascript\n// Using type identifier\nconst $ = _$('string', query =\u003e \n    document.querySelector(query)\n);\n\n$('.my-element');\n\n// Using Custom class\nconst process = _$(\n    CustomType, instance =\u003e instance.process()\n);\n```\n\n### Positional Parameters\n```javascript\nconst add = _$(\n    ['number', 'number'], (a, b) =\u003e a + b\n);\n\nadd(40, 2); // Returns 42\n\nconst delayed = _$(\n    ['int', 'function'], (ms, callback) =\u003e setTimeout(callback, ms)\n);\n\ndelayed(1000, () =\u003e console.log('Done!')); \n```\n\n### Zero Parameter Functions\n\nFor functions that take no parameters, you can use any of these equivalent forms:\n\n```javascript\n// These all create a parameterless function that returns a number\nconst fn1 = _$(undefined, () =\u003e 42, 'number');\nconst fn2 = _$(null, () =\u003e 42, 'number');\nconst fn3 = _$('void', () =\u003e 42, 'number');\nconst fn4 = _$([], () =\u003e 42, 'number');\n\nconst result = fn1();  // Returns 42\nfn1(42);  // Throws: Expected 0 arguments, got 1\n```\n\n### Custom Validators\n\nYou can use functions as input type validators. They **must** be synchronous and return a truthy/falsey value.\n\n```javascript\nconst isEven = n =\u003e n % 2 === 0;\nconst getHalf = _$(isEven, num =\u003e num/2);\ngetHalf(42); // Accepted input\ngetHalf(43); // TypeError\n\n// declared inline\nconst ref = 1;\nconst getExact = _$(\n    a =\u003e a === ref,\n    num =\u003e num\n);\n```\n\n## Error Handling\nThrows a `TypeError` for validation failures:\n\n- Missing required parameters\n- Type mismatches\n- Coercion failures\n- Invalid custom type instances\n\n## Return Type Validation\n\nYou can optionally specify an expected return type as the third parameter.\n\n### Supported Return Types\n\n- All input type identifiers (`'string'`, `'number'`, `'boolean'`, `'null'`, etc)\n- Custom classes (validates instanceof)\n- Regular expressions (tests string conversion)\n- Array of types for multiple options\n- Special types:\n  - `'void'` or `undefined` - Must return undefined\n  - `'any'` - Any value except undefined\n  - `'optional'` - Included for completeness, this is the same as not specifying a return type. Return type is not checked.\n  - `a =\u003e a === b` - Use any declared or inline function to validate output\n  \n### Return Type Examples\n\n```javascript\n// Ensure function returns a string\nconst upperCase = _$(\n    'string', str =\u003e str.toUpperCase(), 'string'\n);\n\n// Validate class instances\n// including custom and built in types\nconst getUser = _$(\n    'number', id =\u003e db.findUser(id), User\n);\n\nconst getNodes = _$(\n    [ Node, 'string' ], (el, q) =\u003e el.querySelectorAll(q), NodeList\n);\n\n// Allow multiple return types\nconst getValue = _$(\n    'string', key =\u003e cache.get(key), ['string', 'null']\n);\n\n// Explicit void return, must return undefined\nconst logMessage = _$(\n    'string', msg =\u003e { console.log(msg); }, 'void'\n);\n\n// Any non-undefined return, null allowed\nconst process = _$(\n    'object', data =\u003e processData(data), 'any'\n);\n\n// Regular Expression test string output\nconst checkValue = _$(\n    'string', str =\u003e procesValue(str), /^testing$/i\n);\n\n// custom validator function\nconst offset = 10;\nconst getPositive = _$(\n    'number', num =\u003e num - offset, n =\u003e n \u003e 0\n);\ngetPositive(5); // returns -5, would fail validation\n\n// check by reference\nconst complexTask = _$(\n    null, doSomething, checkResults\n);\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbesworks%2Fvalidatedmethod","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbesworks%2Fvalidatedmethod","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbesworks%2Fvalidatedmethod/lists"}