{"id":22793080,"url":"https://github.com/kripod/bookshelf-validate","last_synced_at":"2025-04-16T15:51:20.543Z","repository":{"id":74800730,"uuid":"49736052","full_name":"kripod/bookshelf-validate","owner":"kripod","description":"Validation for the Model objects of Bookshelf.js","archived":false,"fork":false,"pushed_at":"2018-11-09T20:43:49.000Z","size":19,"stargazers_count":8,"open_issues_count":3,"forks_count":5,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-29T05:32:48.652Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/kripod.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}},"created_at":"2016-01-15T18:08:31.000Z","updated_at":"2019-03-31T18:38:47.000Z","dependencies_parsed_at":null,"dependency_job_id":"d36960ff-380f-4755-a225-15061d29a9dd","html_url":"https://github.com/kripod/bookshelf-validate","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kripod%2Fbookshelf-validate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kripod%2Fbookshelf-validate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kripod%2Fbookshelf-validate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kripod%2Fbookshelf-validate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kripod","download_url":"https://codeload.github.com/kripod/bookshelf-validate/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249257117,"owners_count":21239139,"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":[],"created_at":"2024-12-12T03:17:56.443Z","updated_at":"2025-04-16T15:51:20.526Z","avatar_url":"https://github.com/kripod.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# bookshelf-validate\n\n[![Version (npm)](https://img.shields.io/npm/v/bookshelf-validate.svg)](https://npmjs.com/package/bookshelf-validate)\n\nValidation for the Model objects of Bookshelf.js\n\n## Installation\n\n```\nnpm install --save bookshelf-validate\n```\n\n## Configuration\n\nTo initialize the plugin, call `bookshelf.plugin('bookshelf-validate'[, config]);`\nwith your Bookshelf instance.\n\nThe `config` object is optional, and the defaults are:\n\n```js\n{\n  validator: require('validator'), // node-validator\n  validateOnSave: false // Automatically validate when Bookshelf emits 'saving' event\n}\n```\n\n### config.validator\n\nBy default, the validation methods are provided by the __validator__ npm package.\n\nYou can pass a different validator object, or customize node-validator by adding\nmethods to it before passing it to the configuration. The only requirement\nis that every method on the validator object takes the value to be validated as the\nfirst argument.\n\nExample by customizing __validator__:\n\n``` js\nvar validator = require('validator');\n\nvalidator.isPrime = function (str) {\n  var value = parseInt(str);\n  if (value === NaN || value \u003c 2) return false;\n\n  for (var i = 2; i \u003c= value \u003e\u003e 1; i++) {\n    if (value % i === 0) {\n      return false;\n    }\n  }\n};\n\nbookshelf.plugin('bookshelf-validate', {\n  validator: validator\n});\n```\n\n### config.validateOnSave\n\nIf `validateOnSave` is `true`, the validations will automatically be called\nwhen Bookshelf emits a `'saving'` event. If any validations fail, an\nerror will be thrown and the model will not be saved.\n\n## API\n\n### 'isRequired'\n\nSince `node-validator` does not look at undefined or null values, an optional\nvalidator `isRequired` is provided with the library. It is off by default.\n\n### Model.validations\n\nTo use `bookshelf-validator` in your models, you must add a `validations`\nkey to your Bookshelf model. Each key of the `validations` object must be\nan attribute of the Bookshelf model. There are four ways to write the\nvalidations for each attribute, depending on the level of specifity you need\nto provide.\n\n#### Option 1: Validation method name as string\n\n```js\nvar User = bookshelf.Model.extend({\n  validations: {\n    username: 'isRequired'\n  }\n});\n```\n\n#### Option 2: Validation method name as key in object\n\nWith this option, the values of the validation method name keys will be passed\nto the validation methods as arguments. An array of values may be passed\nfor arbitrary-arity methods.\n\n```js\nvar User = bookshelf.Model.extend({\n  validations: {\n    username: {\n      isRequired: true,\n      isLength: { min: 2, max: 32 } // will call validator.isLength(value, { min: 2, max: 32 })\n    }\n  }\n});\n```\n\n\n#### Option 3: Validation method with custom error message\n\nWith this option, if the validation fails, your custom error message will be\nreturned instead of the default (the name of the method which failed validation).\nThis is good if you want to send messages to the user about why validation failed.\n\n```js\nvar User = bookshelf.Model.extend({\n  validations: {\n    username: {\n      method: 'isLength',\n      error: 'Your username must be between 4 and 32 characters long.',\n      args: { min: 4, max: 32 }\n    }\n  }\n});\n```\n\nThe `error` and `args` attributes are optional.\n\n#### Option 4: An array with a combination of any of the above\n\nFor more complicated validations, you may pass an array that has a combination\nof strings and objects. If an object has an attribute called `method` it will be\nassumed to be type (3), otherwise it will be type (2). Since you will probably\nnot name a validation method with the name `method`, it is unlikely there will\nbe any problems.\n\n```js\nvar User = bookshelf.Model.extend({\n  validations: {\n    email: [\n      'isRequired',\n      { isEmail: {allow_display_name: true} }, // Options object passed to node-validator\n      { method: 'isLength', error: 'Username 4-32 characters long.', args: { min: 4, max: 32 } } // Custom error message\n    ]\n  }\n});\n```\n\n### Model#validationErrors\n\nCall `validationErrors()` on a model instance to see the results of your validation.\n\nIf there are any invalid attributes on your model, the result will be a\n`ValidationError` object containing an object of attributes and their errors on\nthe `data` property.\n\nIf the `validateOnSave: true` option was configured, `validationErrors()` will\nbe called automatically when you attempt to save the model. If not, you can\ncall it yourself to see the errors before you save the model.\n\n``` js\nvar bookshelf = require('bookshelf');\nvar validator = require('validator');\n\nvalidator.isRequired = function (val) {\n  return val != null;\n}\n\nbookshelf.plugin('bookshelf-validate', {\n  validator: validator,\n  validateOnSave: true\n});\n\nvar User = bookshelf.Model.extend({\n  tableName: 'users',\n  validations: {\n    // Username is required, and its length must be between 2 and 32 characters\n    username: [\n      'isRequired',\n      { method: 'isLength', error: 'Username must be between 2 and 32 characters.', args: { min: 2, max: 32 } }\n    ],\n\n    // Email is required, and must be a valid e-mail address\n    email: [\n      'isRequired',\n      { method: 'isEmail', error: 'Not a valid email address' }\n    ],\n\n    // Birthday is not required, but must be a date if given\n    birthday: { isDate: true } // Same as `birthday: 'isRequired'`\n  }\n});\n\nvar user = new User({\n  username: 'x', // Invalid length\n  birthday: '1997-11-21', // Valid\n  color: 'green' // Not validated\n});\n\nlet errors = user.validationErrors();\nconsole.log(errors);\n/*\n  [ValidationError]:\n  {\n    data: {\n      username: ['Username must be between 2 and 32 characters'],\n      email: ['isRequired']\n    }\n  }\n/*\n```\n\nAnd, if `validateOnSave` is `true`:\n\n```js\nuser.save(); // Throws a ValidationError\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkripod%2Fbookshelf-validate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkripod%2Fbookshelf-validate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkripod%2Fbookshelf-validate/lists"}