{"id":13394433,"url":"https://github.com/busypeoples/spected","last_synced_at":"2025-04-04T11:12:19.497Z","repository":{"id":57367263,"uuid":"94582947","full_name":"busypeoples/spected","owner":"busypeoples","description":"Validation library","archived":false,"fork":false,"pushed_at":"2023-02-03T18:23:20.000Z","size":88,"stargazers_count":702,"open_issues_count":13,"forks_count":32,"subscribers_count":17,"default_branch":"master","last_synced_at":"2025-03-29T04:44:41.569Z","etag":null,"topics":["javascript","nested-objects","spec","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/busypeoples.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}},"created_at":"2017-06-16T21:36:12.000Z","updated_at":"2024-11-18T17:42:51.000Z","dependencies_parsed_at":"2023-02-18T10:00:27.635Z","dependency_job_id":null,"html_url":"https://github.com/busypeoples/spected","commit_stats":null,"previous_names":["25th-floor/spected"],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/busypeoples%2Fspected","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/busypeoples%2Fspected/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/busypeoples%2Fspected/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/busypeoples%2Fspected/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/busypeoples","download_url":"https://codeload.github.com/busypeoples/spected/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247166168,"owners_count":20894654,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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","nested-objects","spec","validation"],"created_at":"2024-07-30T17:01:19.535Z","updated_at":"2025-04-04T11:12:19.475Z","avatar_url":"https://github.com/busypeoples.png","language":"JavaScript","readme":"# Spected\n\n### Validation Library\n\n__Spected__ is a low level validation library for validating objects against defined validation rules.\nFramework specific validation libraries can be built upon __spected__, leveraging the __spected__ appraoch of separating the speciific input from any validation.\nFurthermore it can be used to verify the validity deeply nested objects, f.e. server side validation of data or client side validation of JSON objects.\n__Spected__ can also be used to validate Form inputs etc.\n\n\n### Getting started\n\nInstall Spected via npm or yarn.\n\n\n```\nnpm install --save spected\n```\n\n### Use Case\n__Spected__ takes care of running your predicate functions against provided inputs, by separating the validation from the input.\nFor example we would like to define a number of validation rules for two inputs, _name_ and _random_.\n\n```javascript\nconst validationRules = {\n  name: [\n    [ isGreaterThan(5),\n      `Minimum Name length of 6 is required.`\n    ],\n  ],\n  random: [\n    [ isGreaterThan(7), 'Minimum Random length of 8 is required.' ],\n    [ hasCapitalLetter, 'Random should contain at least one uppercase letter.' ],\n  ]\n}\n```\nAnd imagine this is our input data.\n\n```javascript\nconst inputData = { name: 'abcdef', random: 'z'}\n```\n\nWe would like to have a result that displays any possible errors.\n\nCalling validate `spected(validationRules, inputData)`\nshould return\n\n```javascript\n{name: true,\n random: [\n    'Minimum Random length of 8 is required.',\n    'Random should contain at least one uppercase letter.'\n]}\n```\n\nYou can also pass in an array of items as an input and validate that all are valid.\nYou need to write the appropriate function to handle any specific case.\n\n```javascript\nconst userSpec = [\n  [\n    items =\u003e all(isLengthGreaterThan(5), items),\n    'Every item must have have at least 6 characters!'\n  ]\n]\n\nconst validationRules = {\n  id: [[ notEmpty, notEmptyMsg('id') ]],\n  users: userSpec,\n}\n\nconst input = {\n  id: 4,\n  users: ['foobar', 'foobarbaz']\n}\n\nspected(validationRules, input)\n\n```\n\n##### Validating Dynamic Data\nThere are cases where a validation has to run against an unknown number of items. f.e. submitting a form with dynamic fields.\nThese dynamic fields can be an array or as object keys.\n\n```js\n\nconst input = {\n  id: 4,\n  users: [\n    {firstName: 'foobar', lastName: 'action'},\n    {firstName: 'foo', lastName: 'bar'},\n    {firstName: 'foobar', lastName: 'Action'},\n  ]\n}\n\n```\n\nAll `users` need to run against the same spec.\n\n```js\n\nconst capitalLetterMsg = 'Capital Letter needed.'\n\nconst userSpec = {\n  firstName: [[isLengthGreaterThan(5), minimumMsg('firstName', 6)]],\n  lastName: [[hasCapitalLetter, capitalLetterMsg]],\n}\n\n```\n\nAs we're only dealing with functions, map over `userSpec` and run the predicates against every collection item.\n\n```js\n\nconst validationRules = {\n  id: [[ notEmpty, notEmptyMsg('id') ]],\n  users: map(always(userSpec)),\n}\n\nspected(validationRules, input)\n\n```\n\nIn case of an object containing an unknown number of properties, the approach is the following.\n\n```js\n\nconst input = {\n  id: 4,\n  users: {\n    one: {firstName: 'foobar', lastName: 'action'},\n    two: {firstName: 'foo', lastName: 'bar'},\n    three: {firstName: 'foobar', lastName: 'Action'},\n  }\n}\n\n```\n\nSpected can also work with functions instead of an `[predFn, errorMsg]` tuple array, which means one can specify a function\nthat expects the input and then maps every rule to the object. Note: This example uses Ramda `map`, which expects the\nfunction as the first argument and then always returns the UserSpec for every property.\n\n```js\n\nconst validationRules = {\n  id: [[ notEmpty, notEmptyMsg('id') ]],\n  users: map(() =\u003e userSpec)),\n}\n\n```\n\nHow `UserSpec` is applied to every Object key is not spected specific, but can be freely implemented as needed.\n\nSpected also accepts a function as an input, i.e. to simulate if a field would contain errors if empty.\n\n```\nconst verify = validate(a =\u003e a, a =\u003e a)\nconst validationRules = {\n  name: nameValidationRule,\n}\nconst input = {name: 'foobarbaz'}\nconst result = verify(validationRules, key =\u003e key ? ({...input, [key]: ''}) : input)\ndeepEqual({name: ['Name should not be empty.']}, result)\n\n```\n\n### Basic Example\n\n```js\n\nimport {\n  compose,\n  curry,\n  head,\n  isEmpty,\n  length,\n  not,\n  prop,\n} from 'ramda'\n\nimport spected from 'spected'\n\n// predicates\n\nconst notEmpty = compose(not, isEmpty)\nconst hasCapitalLetter = a =\u003e /[A-Z]/.test(a)\nconst isGreaterThan = curry((len, a) =\u003e (a \u003e len))\nconst isLengthGreaterThan = len =\u003e compose(isGreaterThan(len), prop('length'))\n\n\n// error messages\n\nconst notEmptyMsg = field =\u003e `${field} should not be empty.`\nconst minimumMsg = (field, len) =\u003e `Minimum ${field} length of ${len} is required.`\nconst capitalLetterMsg = field =\u003e `${field} should contain at least one uppercase letter.`\n\n// rules\n\nconst nameValidationRule = [[notEmpty, notEmptyMsg('Name')]]\n\nconst randomValidationRule = [\n  [isLengthGreaterThan(2), minimumMsg('Random', 3)],\n  [hasCapitalLetter, capitalLetterMsg('Random')],\n]\n\nconst validationRules = {\n  name: nameValidationRule,\n  random: randomValidationRule,\n}\n\nspected(validationRules, {name: 'foo', random: 'Abcd'})\n// {name: true, random: true}\n\n```\n\n### Advanced\nA spec can be composed of other specs, enabling to define deeply nested structures to validate against nested input.\nLet's see this in form of an example.\n\n```js\nconst locationSpec = {\n    street: [...],\n    city: [...],\n    zip: [...],\n    country: [...],\n}\n\nconst userSpec = {\n    userName: [...],\n    lastName: [...],\n    firstName: [...],\n    location: locationSpec,\n    settings: {\n        profile: {\n            design: {\n                color: [...]\n                background: [...],\n            }\n        }\n    }\n}   \n```\n\nNow we can validate against a deeply nested data structure.\n\n### Advanced Example\n\n```js\n\nimport {\n  compose,\n  indexOf,\n  head,\n  isEmpty,\n  length,\n  not,\n} from 'ramda'\n\nimport spected from 'spected'\n\nconst colors = ['green', 'blue', 'red']\nconst notEmpty = compose(not, isEmpty)\nconst minLength = a =\u003e b =\u003e length(b) \u003e a\nconst hasPresetColors = x =\u003e indexOf(x, colors) !== -1\n\n// Messages\n\nconst notEmptyMsg = field =\u003e `${field} should not be empty.`\nconst minimumMsg = (field, len) =\u003e `Minimum ${field} length of ${len} is required.`\n\nconst spec = {\n  id: [[notEmpty, notEmptyMsg('id')]],\n  userName: [[notEmpty, notEmptyMsg('userName')], [minLength(5), minimumMsg('userName', 6)]],\n  address: {\n    street: [[notEmpty, notEmptyMsg('street')]],\n  },\n  settings: {\n    profile: {\n      design: {\n        color: [[notEmpty, notEmptyMsg('color')], [hasPresetColors, 'Use defined colors']],\n        background: [[notEmpty, notEmptyMsg('background')], [hasPresetColors, 'Use defined colors']],\n      },\n    },\n  },\n}\n\nconst input = {\n  id: 1,\n  userName: 'Random',\n  address: {\n    street: 'Foobar',\n  },\n  settings: {\n    profile: {\n      design: {\n        color: 'green',\n        background: 'blue',\n      },\n    },\n  },\n}\n\nspected(spec, input)\n\n/* {\n      id: true,\n      userName: true,\n      address: {\n        street: true,\n      },\n      settings: {\n        profile: {\n          design: {\n            color: true,\n            background: true,\n          },\n        },\n      },\n    }\n*/\n```\n\n### Custom Transformations\nIn case you want to change the way errors are displayed, you can use the low level `validate` function, which expects a success and a failure\ncallback in addition to the rules and input.\n\n```js\nimport {validate} from 'spected'\nconst verify = validate(\n    () =\u003e true, // always return true\n    head // return first error message head = x =\u003e x[0]   \n)\nconst spec = {\n  name: [\n    [isNotEmpty, 'Name should not be  empty.']\n  ],\n  random: [\n    [isLengthGreaterThan(7), 'Minimum Random length of 8 is required.'],\n    [hasCapitalLetter, 'Random should contain at least one uppercase letter.'],\n  ]\n}\n\nconst input = {name: 'foobar', random: 'r'}\n\nverify(spec, input)\n\n//  {\n//      name: true,\n//      random: 'Minimum Random length of 8 is required.',\n//  }\n\n\n```\n\nCheck the [API documentation](docs/API.md) for further information.\n\n\n### Further Information\n\nFor a deeper understanding of the underlying ideas and concepts:\n\n[Form Validation As A Higher Order Component Pt.1](https://medium.com/javascript-inside/form-validation-as-a-higher-order-component-pt-1-83ac8fd6c1f0)\n\n### Credits\nWritten by [A.Sharif](https://twitter.com/sharifsbeat)\n\nContributions by\n\n[Paul Grenier](https://github.com/AutoSponge)\n\n[Emilio Srougo](https://github.com/Emilios1995)\n\n[Andrew Palm](https://github.com/apalm)\n\n[Luca Barone](https://github.com/cloud-walker)\n\nand many more.\n\nAlso very special thanks to everyone that has contributed documentation updates and fixes (this list will updated).\n\nOriginal idea and support by [Stefan Oestreicher](https://twitter.com/thinkfunctional)\n\n#### Documentation\n[API](docs/API.md)\n\n### License\n\nMIT\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbusypeoples%2Fspected","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbusypeoples%2Fspected","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbusypeoples%2Fspected/lists"}