{"id":13454658,"url":"https://github.com/nettofarah/property-validator","last_synced_at":"2025-04-09T17:20:54.662Z","repository":{"id":57331779,"uuid":"49801570","full_name":"nettofarah/property-validator","owner":"nettofarah","description":":white_check_mark: Easy property validation for JavaScript, Node and Express.","archived":false,"fork":false,"pushed_at":"2019-12-04T20:59:40.000Z","size":131,"stargazers_count":158,"open_issues_count":3,"forks_count":9,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-02T12:54:08.013Z","etag":null,"topics":["assertions","request-validation","validation","validator"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nettofarah.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-01-17T03:36:36.000Z","updated_at":"2024-01-05T14:05:04.000Z","dependencies_parsed_at":"2022-09-05T08:30:51.985Z","dependency_job_id":null,"html_url":"https://github.com/nettofarah/property-validator","commit_stats":null,"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nettofarah%2Fproperty-validator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nettofarah%2Fproperty-validator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nettofarah%2Fproperty-validator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nettofarah%2Fproperty-validator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nettofarah","download_url":"https://codeload.github.com/nettofarah/property-validator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248074940,"owners_count":21043495,"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":["assertions","request-validation","validation","validator"],"created_at":"2024-07-31T08:00:56.476Z","updated_at":"2025-04-09T17:20:54.644Z","avatar_url":"https://github.com/nettofarah.png","language":"JavaScript","funding_links":[],"categories":["Packages","Repository","包","Data validation","目录","Number"],"sub_categories":["Data validation","Data Validation","数据校验","数据验证"],"readme":"# property-validator\n[![Build Status](https://travis-ci.org/nettofarah/property-validator.svg?branch=master)](https://travis-ci.org/nettofarah/property-validator)\n\n:white_check_mark: Easy property validation for JavaScript, Node and Express\n\nBuilt on top of [validator.js](https://github.com/chriso/validator.js), property-validator makes validating request parameters easy and fun.\nNo chaining, no prototype violations, no magic. Just some simple, stateless, javascript functions.\n\nAll you have to do is import some base validation functions and declare the validation rules for your request.\n\n## Table of contents\n- [Installation](#installation)\n- [Usage](#usage)\n- [Usage in NodeJS](#usage-in-nodejs)\n    - [Request Validation](#request-validation)\n        - [Request Parameters](#request-parameters)\n        - [Query String](#query-string)\n        - [Body](#body)\n        - [Headers](#headers)\n        - [Everything](#everything)\n        - [Assert Middleware](#assert-middleware)\n- [Advanced usage](#advanced-usage)\n    - [Optional Validation](#optional-validation)\n    - [Custom Error Messages](#custom-error-messages)\n    - [Custom localization](#custom-localization)\n    - [Custom Validation Functions](#custom-validation-functions)\n- [Validation Helpers](#validation-helpers)\n    - [Supported Helpers](#supported-helpers)\n    - [Not currently supported](#not-currently-supported)\n- [Usage with TypeScript](#usage-with-typescript)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Installation\n```bash\nnpm install --save property-validator\n```\n\n## Usage\nproperty-validator provides a suite of `validate` and `assert` functions to make request validation simple and easy to write.\n\n`assert` functions halt the programs's execution if one of the validation rules breaks.\n\n```javascript\nimport { assert, presence, email } from 'property-validator';\n\nlet user = {\n  username: 'nettofarah',\n  email_address: 'invalid@email'\n}\n\nassert(user, [\n  presence('username'),\n  email('email_address')\n]);\n\n// will throw a ValidationError\n\n// /Users/netto/projects/property-validator/lib/request_assertions.js:8\n//    throw new ValidationError(validation);\n```\n\n`validate` functions on the other hand, will return an object containing the result of all validations.\n\n```javascript\nimport { validate, presence, email } from 'property-validator';\n\nlet user = {\n  username: 'nettofarah',\n  email_address: 'invalid@email'\n}\n\nvalidate(user, [\n  presence('username'),\n  email('email_address')\n]);\n\n// returns\n{\n  valid: false,\n  errors :[\n    {\n      field: \"email_address\",\n      message: \"\\\"email_address\\\" should look like an email address\"\n    }\n  ],\n  messages: [\n    \"\\\"email_address\\\" should look like an email address\"\n  ]\n}\n```\n\n`property-validator` really shines when you combine it with web servers.\n\n## Usage in NodeJS\n\nYou can run validations and assertions against the request `body`, `query`, `params` and `headers`, or against all of them at once using `assertAll` or `validateAll`.\n\nUsing `assertAll`:\n\n```javascript\nimport express from 'express';\nimport { assertAll, presence, email, assertMiddleware } from 'property-validator';\n\nconst app = express();\n\napp.get('/hello', function(req, res){\n  assertAll(req, [\n    presence('username'),\n    email('email_address')\n  ]);\n\n  res.status(200).json({ name: req.query.username });\n});\n\napp.use(assertMiddleware);\n```\n\n### Request Validation\nproperty-validator offers out of the box support for request params, query\nstring, body and header validations.\n\nAll you have to do is to import the correct function and annotate your request\nhandler.\n\n#### Request Parameters\n\nYou can run validations against incoming request params.\n\n```javascript\nimport { validateParams, presence } from 'property-validator';\n\napp.get('/hello/:username', function(req, res){\n  const validation = validateParams(req, [\n    presence('username')\n  ]);\n\n  if (validation.valid) {\n    res.status(200).json({ name: req.query.username });\n  } else {\n    res.status(422).json({ errors: validation.errors });\n  }\n});\n```\n\nor use the `assertParams` counterpart:\n```javascript\nimport { assertParams, presence } from 'property-validator';\n\napp.get('/hello/:username', function(req, res){\n  assertParams(req, [\n    presence('username')\n  ]);\n\n  // No need to check the validation result\n  res.status(200).json({ name: req.query.username });\n});\n```\n\n#### Query String\n\n```javascript\nimport { validateQuery, email } from 'property-validator';\n\napp.get('/hi', function(req, res){\n  const validation = validateQuery(req, [\n    email('primary_email_address')\n  ]);\n\n  if (validation.valid) {\n    res.status(200).send('We promise not to send spam!');\n  } else {\n    res.status(422).json({ errors: validation.errors });\n  }\n});\n```\n\nor use the `assertQuery` counterpart:\n```javascript\nimport { assertQuery, email } from 'property-validator';\n\napp.get('/hi', function(req, res){\n  assertQuery(req, [\n    email('primary_email_address')\n  ]);\n\n  // No need to check the validation result\n  res.status(200).send('We promise not to send spam!');\n});\n```\n\n#### Body\n\n```javascript\nimport { validateBody, presence, email } from 'property-validator';\n\napp.post('/sign-up', function(req, res){\n  const validation = validateBody(req, [\n    email('user.email'),\n    presence('user.password'),\n    presence('user.password_confirmation')\n  ]);\n\n  if (validation.valid) {\n    res.status(200).send('Welcome!');\n  } else {\n    res.status(422).send({ errors: validation.errors });\n  }\n});\n```\nor use the `assertBody` counterpart:\n\n```javascript\nimport { assertBody, presence, email } from 'property-validator';\n\napp.post('/sign-up', function(req, res){\n  assertBody(req, [\n    email('user.email'),\n    presence('user.password'),\n    presence('user.password_confirmation')\n  ]);\n\n  // No need to check the validation result\n  res.status(200).send('Welcome!');\n});\n```\n\n#### Headers\n```javascript\nimport { validateHeaders, presence, format } from 'property-validator';\n\napp.get('/secret-stuff', function(req, res){\n  const validation = validateHeaders(req, [\n    presence('Authorization'),\n    format('Authorization', /Token token=\"\\w+\"/)\n  ]);\n\n  if (validation.valid) {\n    res.status(200).send('Here is all your secret stuff!');\n  } else {\n    res.status(401).send('You shall not pass!');\n  }\n});\n```\n\nor use the `assertHeaders` counterpart:\n\n```javascript\nimport { assertHeaders, presence, format } from 'property-validator';\n\napp.get('/secret-stuff', function(req, res){\n  assertHeaders(req, [\n    presence('Authorization'),\n    format('Authorization', /Token token=\"\\w+\"/)\n  ]);\n\n  // No need to check the validation result\n  res.status(200).send('Here is all your secret stuff!');\n});\n```\n\n#### Everything\nYou can use `validateAll` or `assertAll` to run validation rules against all properties at once (`body`, `params`, `query`).\nImportant: `validateAll` and `assertAll` will not run validations agains `headers` since they're pretty different use cases.\n\n#### Assert Middleware\nproperty-validator ships with a standard middleware that automatically handles assert errors.\nAll you have to do is to import `assertMiddleware` and mount it after all request handlers in your express app.\n\n```javascript\nimport express from 'express';\nimport { assertAll, presence, email, assertMiddleware } from 'property-validator';\n\nconst app = express();\n\napp.get('/hello', function(req, res){\n  assertAll(req, [\n    presence('username'),\n    email('email_address')\n  ]);\n\n  res.status(200).json({ name: req.query.username });\n});\n\napp.post('/bla', ...);\n...\n\napp.get('/test', ...);\n\napp.use(assertMiddleware);\n```\n\nYou can also roll your own middleware in case you need any sort of customization.\n\n```javascript\nimport { ValidationError } from 'property-validator';\n\napp.use(function(err, req, res, next) {\n  // Do not swallow all kinds of errors\n  const isValidationError = (err instanceof ValidationError);\n  if (!isValidationError) {\n    return next(err);\n  }\n\n  const messages = err.messages;\n  res.status(422);\n\n  res.json({\n    notice: \"Your request is invalid\",\n    errors: messages\n  })\n});\n```\n\n---\n\n## Advanced usage\n\nproperty-validator is extensible. You can set optional property validation, customize your custom messages and write your own validation functions.\n\n### Optional Validation\n`optional` is a special validation helper that can be used when fields are not\nstrictly required, but need to be validated in case they are present.\n\nYou can pass in any other validation helper, and propery-validator will only run\nthe helper function against the input params if the optional field is present.\n\nPagination is usually a good use case for optional params:\n\n```javascript\nvar validation = validate(params, [\n  optional(isNumeric('limit')),\n  optional(isNumeric('offset'))\n]);\n```\n\n### Custom Error Messages\nValidation helpers allow custom messages to be set.\nYou can set the validation message to any string you want.\n\nAll you need to do is to pass in a custom error message as the last param when\ncalling any validation helper.\n\n```javascript\nvar validation = validate(params, [\n  presence('name', 'Oops, you forgot to tell us your name'),\n  isCurrency('rent_in_brl', { symbol: 'R$' }, 'Reais should be prefixed with R$'),\n  isCurrency('rent', 'This does not look like money')\n]);\n```\n\nIt is also possible to use some of the parameters of your validator in the error message.\n\n```javascript\nvar validation = validate(params, [\n  presence('name', 'Oops, you forgot to tell us your :paramName'),\n  isLength('value', { min: 10, max: 99 }, 'The :paramName should be between :min and :max')\n]);\n\n//Oops, you forgot to tell us your name\n//The value should be between 10 and 99\n```\n\n### Custom localization\nIt is possible to override the default locals. The locals is a simple object with keys refering to a validation function and there value the message.\n\n```javascript\nimport { assert, presence, isLength, email, setLocals } from 'property-validator';\nsetLocals({\n  required: 'Oops, you forgot to tell us your :paramName'\n});\n\nvar validation = validate(params, [\n  presence('name'),\n  isLength('value', { min: 10, max: 99 }, 'The :paramName should be between :min and :max'),\n  email('email')\n]);\n\n//Oops, you forgot to tell us your name\n//The value should be between 10 and 99\n//\"email\" should look like an email address\n```\nAs you can see all kind of combinations are possible. You can override the default locals and still set a custom message. \nAnd if you neither supply a translation through the setLocals nor set a custom message, it will fall back to the default locals.\n\nIf you would like to restore the locals to the default locals simply call `restoreDefaultLocals` like so:\n\n```javascript\nimport { restoreDefaultLocals } from 'property-validator';\n\nrestoreDefaultLocals();\n```\n\n### Custom Validation Functions\nWriting your own validation functions is easy.\n\n```javascript\n// Your function will receive a property name as its argument\nfunction isTheUltimateAnswer(propertyName) {\n  // and then return a function that takes the\n  // actual object you want to validate\n  return function(subject) {\n    var value = subject[propertyName]\n    var isAnswer = value === 42\n\n    // Make sure your function returns `result`, `message`\n    // and `field`\n    return {\n      result: isAnswer,\n      message: value + \" is not the Answer to the Ultimate Question of Life, The Universe, and Everything\",\n      field: propertyName\n    }\n  }\n}\n```\n\nYou can now use your custom function as you would with any other validation helper:\n\n```javascript\nvar subject = {\n  'guess': 43\n}\n\nvar validation = validate(subject, [\n  isTheUltimateAnswer('guess')\n]);\n```\n\n---\n\n## Validation Helpers\nValidation helpers are functions you can use to validate incoming request properties.\n\nproperty-validator relies on the super battle tested [validator.js](https://github.com/chriso/validator.js) library.\n\n### Supported Helpers\nHere's a list of currently supported helpers:\n\n| Helper | Description |\n|--------|-------------|\n|presence(paramName)| check if the current param is present. |\n|optional(validationHelper(paramName, ...)) | takes in another validation helper and only runs the validation if the optional field is present. |\n|oneOf(paramName, optionList)| checks if the input param is one of the values within a list of valid options. |\n|contains(paramName, seed)| check if the string contains the seed. |\n|equals(paramName, comparison)| check if the string matches the comparison. |\n|isAlpha(paramName)| check if the string contains only letters (a-zA-Z). |\n|isAlphanumeric(paramName)| check if the string contains only letters and numbers. |\n|isArray(paramName)| check if the current param is an array. |\n|isCreditCard(paramName)| check if the string is a credit card. |\n|isCurrency(paramName, options)| check if the string is a valid currency amount. `options` is an object which defaults to `{symbol: '$', require_symbol: false, allow_space_after_symbol: false, symbol_after_digits: false, allow_negatives: true, parens_for_negatives: false, negative_sign_before_digits: false, negative_sign_after_digits: false, allow_negative_sign_placeholder: false, thousands_separator: ',', decimal_separator: '.', allow_space_after_digits: false }`. |\n|isDate(paramName)| check if the string is a date. |\n|isDecimal(paramName)| check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc. |\n|isEmail(paramName [, options])| check if the string is an email. `options` is an object which defaults to `{ allow_display_name: false, allow_utf8_local_part: true, require_tld: true }`. If `allow_display_name` is set to true, the validator will also match `Display Name \u003cemail-address\u003e`. If `allow_utf8_local_part` is set to false, the validator will not allow any non-English UTF8 character in email address' local part. If `require_tld` is set to false, e-mail addresses without having TLD in their domain will also be matched. |\n|isIn(paramName, values)| check if the string is in a array of allowed values. |\n|isInt(paramName [, options])| check if the string is an integer. `options` is an object which can contain the keys `min` and/or `max` to check the integer is within boundaries (e.g. `{ min: 10, max: 99 }`). |\n|isJSON(paramName)| check if the string is valid JSON (note: uses JSON.parse). |\n|isNull(paramName)| check if the string is null. |\n|isNumeric(paramName)| check if the string contains only numbers. |\n|isURL(paramName [, options])| check if the string is an URL. `options` is an object which defaults to `{ protocols: ['http','https','ftp'], require_tld: true, require_protocol: false, require_valid_protocol: true, allow_underscores: false, host_whitelist: false, host_blacklist: false, allow_trailing_dot: false, allow_protocol_relative_urls: false }`. |\n|isUUID(paramName [, version])| check if the string is a UUID (version 3, 4 or 5). |\n|matches(paramName, pattern [, modifiers])| check if string matches the pattern. Either `matches('foo', /foo/i)` or `matches('foo', 'foo', 'i')`. |\n|isPlainObject(paramName)| check if the current param is a plain object. |\n|isLength(paramName, options) | check if the string's length falls in a range. Note: this function takes into account surrogate pairs. `options` is an object which can contain the keys `min` and/or `max` to check the integer is within boundaries (e.g. `{ min: 10, max: 99 }`). |\n\n### Not currently supported\nThese are a few other helpers avaliable in [validator.js](https://github.com/chriso/validator.js) that could be used in property-validator.\nFeel free to submit a PR if you need any of these functions.\n\n| Helper | Description |\n|--------|-------------|\n| isAfter(paramName [, date]) | check if the string is a date that's after the specified date (defaults to now). |\n| isAscii(paramName) | check if the string contains ASCII chars only. |\n| isBase64(paramName) | check if a string is base64 encoded. |\n| isBefore(paramName [, date]) | check if the string is a date that's before the specified date. |\n| isBoolean(paramName) | check if a string is a boolean. |\n| isByteLength(paramName, min [, max]) | check if the string's length (in bytes) falls in a range. |\n| isDivisibleBy(paramName, number) | check if the string is a number that's divisible by another. |\n| isFQDN(paramName [, options]) | check if the string is a fully qualified domain name (e.g. domain.com). `options` is an object which defaults to `{ require_tld: true, allow_underscores: false, allow_trailing_dot: false }`. |\n| isFloat(paramName [, options]) | check if the string is a float. `options` is an object which can contain the keys `min` and/or `max` to validate the float is within boundaries (e.g. `{ min: 7.22, max: 9.55 }`). |\n| isFullWidth(paramName) | check if the string contains any full-width chars. |\n| isHalfWidth(paramName) | check if the string contains any half-width chars. |\n| isHexColor(paramName) | check if the string is a hexadecimal color. |\n| isHexadecimal(paramName) | check if the string is a hexadecimal number. |\n| isIP(paramName [, version]) | check if the string is an IP (version 4 or 6). |\n| isISBN(paramName [, version]) | check if the string is an ISBN (version 10 or 13). |\n| isISIN(paramName) | check if the string is an [ISIN][ISIN] (stock/security identifier). |\n| isISO8601(paramName) | check if the string is a valid [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date. |\n| isLowercase(paramName) | check if the string is lowercase. |\n| isMACAddress(paramName) | check if the string is a MAC address. |\n| isMobilePhone(paramName, locale) | check if the string is a mobile phone number, (locale is one of `['zh-CN', 'zh-TW', 'en-ZA', 'en-AU', 'en-HK', 'pt-PT', 'fr-FR', 'el-GR', 'en-GB', 'en-US', 'en-ZM', 'ru-RU', 'nb-NO', 'nn-NO', 'vi-VN', 'en-NZ', 'en-IN']`). |\n| isMongoId(paramName) | check if the string is a valid hex-encoded representation of a [MongoDB ObjectId][mongoid]. |\n| isMultibyte(paramName) | check if the string contains one or more multibyte chars. |\n| isSurrogatePair(paramName) | check if the string contains any surrogate pairs chars. |\n| isUppercase(paramName) | check if the string is uppercase. |\n| isVariableWidth(paramName) | check if the string contains a mixture of full and half-width chars. |\n| isWhitelisted(paramName, chars) | checks characters if they appear in the whitelist. |\n\n## Usage with TypeScript\n\nThere is no need to install additional type definitions for property-validator since it ships with TypeScript definition files.\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/nettofarah/property-validator. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Code of Conduct](https://github.com/nettofarah/property-validator/blob/master/CODE_OF_CONDUCT.md).\n\nTo run the specs check out the repo and follow these steps:\n\n```bash\n$ npm install\n$ npm run test\n```\n\n## License\n\nThe module is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnettofarah%2Fproperty-validator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnettofarah%2Fproperty-validator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnettofarah%2Fproperty-validator/lists"}