{"id":20393553,"url":"https://github.com/chantouchsek/validatorjs","last_synced_at":"2025-04-12T12:05:50.142Z","repository":{"id":36988143,"uuid":"281904238","full_name":"chantouchsek/validatorjs","owner":"chantouchsek","description":"The validator-js library makes data validation in JavaScript very easy in both the browser and Node.js.","archived":false,"fork":false,"pushed_at":"2024-05-27T00:20:10.000Z","size":3488,"stargazers_count":17,"open_issues_count":4,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-05-28T23:48:10.634Z","etag":null,"topics":["javascript","validation","validator","validator-js","validatorjs"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","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/chantouchsek.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","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},"funding":{"patreon":"chantouch"}},"created_at":"2020-07-23T09:07:47.000Z","updated_at":"2024-05-30T08:18:36.520Z","dependencies_parsed_at":"2024-02-02T12:41:21.788Z","dependency_job_id":"4bcf8397-e167-4c7b-ae44-40cace7876d7","html_url":"https://github.com/chantouchsek/validatorjs","commit_stats":{"total_commits":595,"total_committers":7,"mean_commits":85.0,"dds":0.4369747899159664,"last_synced_commit":"e17c6bf24ce6791b833c3b6c98cbf9a520b02667"},"previous_names":["chantouchsek/validator-js"],"tags_count":39,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chantouchsek%2Fvalidatorjs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chantouchsek%2Fvalidatorjs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chantouchsek%2Fvalidatorjs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chantouchsek%2Fvalidatorjs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chantouchsek","download_url":"https://codeload.github.com/chantouchsek/validatorjs/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248565068,"owners_count":21125415,"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","validation","validator","validator-js","validatorjs"],"created_at":"2024-11-15T03:49:18.107Z","updated_at":"2025-04-12T12:05:50.119Z","avatar_url":"https://github.com/chantouchsek.png","language":"TypeScript","readme":"# ValidatorJs\n\n[![ci](https://github.com/chantouchsek/validator-js/actions/workflows/ci.yml/badge.svg)](https://github.com/chantouchsek/validator-js/actions/workflows/ci.yml)\n[![Latest Version on NPM](https://img.shields.io/npm/v/@chantouchsek/validatorjs.svg?style=flat-square)](https://npmjs.com/package/@chantouchsek/validatorjs)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE)\n[![npm](https://img.shields.io/npm/dt/@chantouchsek/validatorjs.svg?style=flat-square)](https://npmjs.com/package/@chantouchsek/validatorjs)\n[![npm](https://img.shields.io/npm/dm/@chantouchsek/validatorjs.svg?style=flat-square)](https://npmjs.com/package/@chantouchsek/validatorjs)\n[![code style](https://antfu.me/badge-code-style.svg)](https://github.com/antfu/eslint-config)\n\nThe ValidatorJs library makes data validation in JavaScript very easy in both the browser and Node.js. This library was\nforked from [ValidatorJs](https://github.com/mikeerickson/validatorjs) to re-write in typescript to add more rules and\nfeatures.\n\n## Why use ValidatorJs?\n\n- Works in both the browser and Node.\n- Readable and declarative validation rules.\n- Error messages with multilingual support.\n- CommonJS/Browserify support.\n- ES6 support.\n- Re-written in Typescript\n\n## Installation\n\n### Using pnpm\n\n```bash\npnpm add @chantouchsek/validatorjs\n```\n\n### Using npm\n\n```bash\nnpm install @chantouchsek/validatorjs\n```\n\n### Using yarn\n\n```bash\nyarn add @chantouchsek/validatorjs\n```\n\n### Basic Usage\n\n```js\nimport { Validator } from '@chantouchsek/validatorjs'\n\nconst validation = new Validator(data, rules, options)\n```\n\n**data** {Object} - The data you want to validate\n\n**rules** {Object} - Validation rules\n\n**options** {Object} - Optional custom **options** to return\n\n- Options\n  - locale?: string | Optional passing locale from config\n  - confirmedReverse?: boolean | Optional showing error message on confirmation field instead of password\n  - customMessages?: Record\u003cstring, any\u003e | Optional custom error messages to return\n  - customAttributes?: Record\u003cstring, any\u003e | Optional custom attribute name to return\n  - defaultAttributeName?: Record\u003cLangTypes, string\u003e | Optional replace all :attribute property with languages provided\n\n#### Example 1 - Passing Validation\n\n```js\nconst data = {\n  age: 28,\n  email: 'johndoe@gmail.com',\n  name: 'John',\n}\n\nconst rules = {\n  age: 'min:18',\n  email: 'required|email',\n  name: 'required',\n}\n\nconst validation = new Validator(data, rules)\n\nvalidation.passes() // true\nvalidation.fails() // false\n```\n\nTo apply validation rules to the _data_ object, use the same object key names for the _rules_ object.\n\n#### Example 2 - Failing Validation\n\n```js\nconst validation = new Validator(\n  {\n    email: 'not an email address.com',\n    name: 'D',\n  },\n  {\n    email: 'required|email',\n    name: 'size:3',\n  },\n)\n\nvalidation.fails() // true\nvalidation.passes() // false\n\n// Error messages\nvalidation.errors.first('email') // 'The email format is invalid.'\nvalidation.errors.get('email') // returns an array of all email error messages\n```\n\n#### Example 3 - With Default Attribute Name\n\n```ts\nconst validation = new Validator(\n  {\n    email: 'not an email address.com',\n    name: 'D',\n  },\n  {\n    email: 'required|email',\n    name: 'size:3',\n  },\n  {\n    defaultAttributeName: {\n      en: '',\n      ja: 'この項目',\n    },\n  }\n)\n\nvalidation.fails() // true\nvalidation.passes() // false\n\n// Error messages\nvalidation.errors.first('email') // 'The field format is invalid.'\nvalidation.errors.first('email') // 'この項目は正しいメールアドレスを入力してください。'\nvalidation.errors.get('email') // returns an array of all email error messages\n```\n\n### Nested Rules\n\nNested objects can also be validated. There are two ways to declare validation rules for nested objects. The first way\nis to declare the validation rules with a corresponding nested object structure that reflects the data. The second way\nis to declare validation rules with flattened key names. For example, to validate the following data:\n\n```js\nconst data = {\n  bio: {\n    age: 28,\n    education: {\n      primary: 'Elementary School',\n      secondary: 'Secondary School',\n    },\n  },\n  name: 'John',\n}\n```\n\nWe could declare our validation rules as follows:\n\n```js\nconst nested = {\n  bio: {\n    age: 'min:18',\n    education: {\n      primary: 'string',\n      secondary: 'string',\n    },\n  },\n  name: 'required',\n}\n\n// OR\n\nconst flattened = {\n  'bio.age': 'min:18',\n  'bio.education.primary': 'string',\n  'bio.education.secondary': 'string',\n  'name': 'required',\n}\n```\n\n### WildCards Rules\n\nWildCards can also be validated.\n\n```js\nconst data = {\n  users: [\n    {\n      bio: {\n        age: 28,\n        education: {\n          primary: 'Elementary School',\n          secondary: 'Secondary School',\n        },\n      },\n      name: 'John',\n    },\n  ],\n}\n```\n\nWe could declare our validation rules as follows:\n\n```js\nconst rules = {\n  'users.*.bio.age': 'min:18',\n  'users.*.bio.education.primary': 'string',\n  'users.*.bio.education.secondary': 'string',\n  'users.*.name': 'required',\n}\n```\n\n### Available Rules\n\nValidation rules do not have an implicit 'required'. If a field is _undefined_ or an empty string, it will pass\nvalidation. If you want a validation to fail for undefined or '', use the _required_ rule.\n\n#### accepted\n\nThe field under validation must be yes, on, 1 or true. This is useful for validating \"Terms of Service\" acceptance.\n\n#### after:date\n\nThe field under validation must be after the given date.\n\n#### after_or_equal:date\n\nThe field under validation must be after or equal to the given field\n\n#### alpha\n\nThe field under validation must be entirely alphabetic characters.\n\n#### alpha_dash\n\nThe field under validation may have alphanumeric characters, as well as dashes and underscores.\n\n#### alpha_num\n\nThe field under validation must be entirely alphanumeric characters.\n\n#### array\n\nThe field under validation must be an array.\n\n#### before:date\n\nThe field under validation must be before the given date.\n\n#### before_or_equal:date\n\nThe field under validation must be before or equal to the given date.\n\n#### between:min,max\n\nThe field under validation must have a size between the given min and max. Strings, numerics, and files are evaluated in\nthe same fashion as the size rule.\n\n#### boolean\n\nThe field under validation must be a boolean value of the form `true`, `false`, `0`, `1`, `'true'`, `'false'`, `'0'`\n, `'1'`,\n\n#### confirmed\n\nThe field under validation must have a matching field of foo_confirmation. For example, if the field under validation is\npassword, a matching password_confirmation field must be present in the input.\n\n#### date\n\nThe field under validation must be a valid date format which is acceptable by Javascript's `Date` object.\n\n#### digits:value\n\nThe field under validation must be numeric and must have an exact length of value.\n\n#### digits_between:min,max\n\nThe field under validation must be numeric and must have length between given min and max.\n\n#### different:attribute\n\nThe given field must be different from the field under validation.\n\n#### email\n\nThe field under validation must be formatted as an e-mail address.\n\n#### hex\n\nThe field under validation should be a hexadecimal format. Useful in combination with other rules, like `hex|size:6` for\nhex color code validation.\n\n#### in:foo,bar,...\n\nThe field under validation must be included in the given list of values. The field can be an array or string.\n\n#### integer\n\nThe field under validation must have an integer value.\n\n#### max:value\n\nValidate that an attribute is no greater than a given size\n\n_Note: Maximum checks are inclusive._\n\n#### Example 1 - Max validation\n\n```js\nconst rules = {\n  phone: 'required|digits|max:11',\n}\nconst input = {\n  phone: '01234567890',\n}\n// passes: true\n```\n\n#### Example 2 - Max validation\n\n```js\nconst rules = {\n  phone: 'integer|max:16',\n}\nconst input = {\n  phone: '18',\n}\n// passes: false\n```\n\n#### min:value\n\nValidate that an attribute is at least a given size.\n\n_Note: Minimum checks are inclusive._\n\n#### Example 1 - Min validation\n\n```js\nconst rules = {\n  phone: 'required|digits|min:11',\n}\nconst input = {\n  phone: '01234567890',\n}\n// passes: true\n```\n\n#### Example 2 - Min validation\n\n```js\nconst rules = {\n  phone: 'integer|min:11',\n}\nconst input = {\n  phone: '18',\n}\n// passes: false\n```\n\n#### not_in:foo,bar,...\n\nThe field under validation must not be included in the given list of values.\n\n#### numeric\n\nValidate that an attribute is numeric. The string representation of a number will pass.\n\n```js\nconst rules = {\n  amount: 'numeric|digits:5',\n}\n```\n\n#### present\n\nThe field under validation must be present in the input data but can be empty.\n\n#### required\n\nChecks if the length of the String representation of the value is \u003e\n\n#### required_if:another_field,value\n\nThe field under validation must be present and not empty if the another field is equal to any value.\n\n#### required_unless:another_field,value\n\nThe field under validation must be present and not empty unless the another field is equal to any value.\n\n#### required_with:foo,bar,...\n\nThe field under validation must be present and not empty only if any of the other specified fields are present.\n\n#### required_with_all:foo,bar,...\n\nThe field under validation must be present and not empty only if all the other specified fields are present.\n\n#### required_without:foo,bar,...\n\nThe field under validation must be present and not empty only when any of the other specified fields are not present.\n\n#### required_without_all:foo,bar,...\n\nThe field under validation must be present and not empty only when all the other specified fields are not present.\n\n#### sometimes\n\nIn some situations, you may wish to run validation checks against a field only if that field is present in the data being validated. To quickly accomplish this, add the sometimes rule to your rule list:\n\n```js\nconst rules = {\n  email: 'sometimes|required|email',\n}\n```\n\nIn the example above, the email field will only be validated if it is present in the input.\n\n#### same:attribute\n\nThe given field must match the field under validation.\n\n#### size:value\n\nThe field under validation must have a size matching the given value. For string data, value corresponds to the number\nof characters. For numeric data, value corresponds to a given integer value.\n\n#### string\n\nThe field under validation must be a string.\n\n#### url\n\nValidate that an attribute has a valid URL format\n\n#### regex:pattern\n\nThe field under validation must match the given regular expression.\n\n**Note**: When using the `regex` pattern, it may be necessary to specify rules in an array instead of using pipe\ndelimiters, especially if the regular expression contains a pipe character. For each backward slash that you used in\nyour regex pattern, you must escape each one with another backward slash.\n\n#### Example 3 - Regex validation\n\n```js\nconst validation = new Validator(\n  {\n    name: 'Doe',\n    salary: '10,000.00',\n    yearOfBirth: '1980',\n  },\n  {\n    name: 'required|size:3',\n    salary: ['required', 'regex:/^(?!0\\\\.00)\\\\d{1,3}(,\\\\d{3})*(\\\\.\\\\d\\\\d)?$/'],\n    yearOfBirth: ['required', 'regex:/^(19|20)[\\\\d]{2,2}$/'],\n  },\n)\n\nvalidation.fails() // false\nvalidation.passes() // true\n```\n\n#### Example 4 - Type Checking Validation\n\n```js\nconst validation = new Validator(\n  {\n    age: 30,\n    name: '',\n  },\n  {\n    age: ['required', { in: [29, 30] }],\n    name: [{ required_if: ['age', 30] }],\n  },\n)\n\nvalidation.fails() // true\nvalidation.passes() // false\n```\n\n### Register Custom Validation Rules\n\n```js\nValidator.register(name, callbackFn, errorMessage)\n```\n\n**name** {String} - The name of the rule.\n\n**callbackFn** {Function} - Returns a boolean to represent a successful or failed validation.\n\n**errorMessage** {String} - An optional string where you can specify a custom error message. _:attribute_ inside\nerrorMessage will be replaced with the attribute name.\n\n```js\nValidator.register(\n  'telephone',\n  (value, requirement, attribute) =\u003e {\n    // requirement parameter defaults to null\n    return value.match(/^\\d{3}-\\d{3}-\\d{4}$/)\n  },\n  'The :attribute phone number is not in the format XXX-XXX-XXXX.',\n)\n```\n\n### Asynchronous Validation\n\nRegister an asynchronous rule which accepts a `passes` callback:\n\n```js\nValidator.registerAsync('username_available', (username, attribute, req, passes) =\u003e {\n  // do your database/api checks here etc\n  // then call the `passes` method where appropriate:\n  passes() // if username is available\n  passes(false, 'Username has already been taken.') // if username is not available\n})\n```\n\nThen call your validator using `checkAsync` passing `fails` and `passes` callbacks like so:\n\n```js\nconst validator = new Validator(\n  {\n    username: 'test123',\n  },\n  {\n    username: 'required|min:3|username_available',\n  },\n)\n\nfunction passes() {\n  // Validation passed\n}\n\nfunction fails() {\n  validator.errors.first('username')\n}\n\nvalidator.checkAsync(passes, fails)\n```\n\n### Working with validated input\n\nUse `validated()` method to retrieve only the validated data and to filter out attributes not found on rules provided.\n\n```js\nconst validation = new Validator(\n  {\n    age: 28,\n    email: 'johndoe@gmail.com',\n    gender: 'male',\n    name: 'John',\n  },\n  {\n    age: 'min:18',\n    name: 'required',\n  },\n)\nvalidation.validated() // will return `{ \"name\": \"John\", \"age\": 28 }`\n```\n\n`validated()` method will throw an error when current validation is failing.\n\n```js\nconst validation = new Validator(\n  {\n    age: 28,\n    email: 'johndoe@gmail.com',\n    gender: 'male',\n    name: 'John',\n  },\n  {\n    age: 'min:40',\n    name: 'required',\n  },\n)\nvalidation.validated() // will throw `Error('Validation failed!')`\n```\n\n`validated()` method also works with asynchronous validation. In this case,\n`passes()` callback will receive only the validated data (without the\nattributes not found on rules provided) as the first argument.\n\n```js\nconst validation = new Validator(\n  {\n    age: 28,\n    email: 'johndoe@gmail.com',\n    gender: 'male',\n    name: 'John',\n  },\n  {\n    age: 'min:18',\n    name: 'required|some_async_rule',\n  },\n)\nfunction passes(validated) {\n  console.log(validated) // will output `{ \"name\": \"John\", \"age\": 28 }` if `some_async_rule` validates `'John'`\n}\nfunction fails() {\n  // will be called if `some_async_rule` does not validate `'John'`\n}\nvalidation.validated(passes, fails)\n```\n\n### Error Messages\n\nThis constructor will automatically generate error messages for validation rules that failed.\n\nIf there are errors, the Validator instance will have its **errors** property object populated with the error messages\nfor all failing attributes. The methods and properties on the **errors** property object are:\n\n#### .first(attribute)\n\nreturns the first error message for an attribute, false otherwise\n\n#### .get(attribute)\n\nreturns an array of error messages for an attribute, or an empty array if there are no errors\n\n#### .all()\n\nreturns an object containing all error messages for all failing attributes\n\n#### .has(attribute)\n\nreturns true if error messages exist for an attribute, false otherwise\n\n#### .errorCount\n\nthe number of validation errors\n\n```js\nconst validation = new Validator(input, rules)\nvalidation.errors.first('email') // returns first error message for email attribute\nvalidator.errors.get('email') // returns an array of error messages for the email attribute\n```\n\n### Custom Error Messages\n\nIf you need a specific error message, and you don't want to override the default one, you can pass an override as the\nthird argument to the Validator object, just like\nwith [Laravel](http://laravel.com/docs/validation#custom-error-messages).\n\n```js\nconst input = {\n  name: '',\n}\n\nconst rules = {\n  name: 'required',\n}\n\nconst validation = new Validator(input, rules, {\n  required: 'You forgot to give a :attribute',\n})\nvalidation.passes()\nvalidation.errors.first('name') // returns 'You forgot to give a name'\n```\n\nSome validators have string and numeric versions. You can change them too.\n\n```js\nconst input = {\n  username: 'myusernameistoolong',\n}\n\nconst rules = {\n  username: 'max:16',\n}\n\nconst validation = new Validator(input, rules, {\n  max: {\n    string: 'The :attribute is too long. Max length is :max.',\n  },\n})\nvalidation.passes()\nvalidation.errors.first('username') // returns 'The username is too long. Max length is 16.'\n```\n\nYou can even provide error messages on a per-attribute basis! Just set the message's key to 'validator.attribute'\n\n```js\nconst input = { email: '', name: '' }\nconst rules = { email: 'required', name: 'required' }\n\nconst validation = new Validator(input, rules, {\n  'required.email': 'Without an :attribute we can\\'t reach you!',\n})\n\nvalidation.passes()\nvalidation.errors.first('name') // returns  'The name field is required.'\nvalidation.errors.first('email') // returns 'Without an email we can\\'t reach you!'\n```\n\n### Custom Attribute Names\n\n#### Using config for custom attribute name\n\n```js\nconst validator = new Validator(\n  { form: { name: null } },\n  { form: { age: 'required', name: 'required' } },\n  {\n    customAttributes: { form: { name: 'Username' } },\n    customMessages: {\n      required: 'The :attribute need to be filled.',\n    },\n  },\n)\nif (validator.fails())\n  validator.errors.first('form.name') // \"The Userame need to be filled.\"\n```\n\nTo display a custom \"friendly\" attribute name in error messages, use `.setAttributeNames()`\n\n```js\nconst validator = new Validator({ name: '' }, { name: 'required' })\nvalidator.setAttributeNames({ name: 'custom_name' })\nif (validator.fails())\n  validator.errors.first('name') // \"The custom_name field is required.\"\n```\n\nAlternatively you can supply global custom attribute names in your lang with the `attributes` property.\n\nYou can also configure a custom attribute formatter:\n\n```js\n// Configure global formatter.\nValidator.setAttributeFormatter((attribute) =\u003e {\n  return attribute.replace(/_/g, ' ')\n})\n\n// Or configure formatter for particular instance.\nconst validator = new Validator({ first_name: '' }, { first_name: 'required' })\nvalidator.setAttributeFormatter((attribute) =\u003e {\n  return attribute.replace(/_/g, ' ')\n})\nif (validator.fails())\n  console.log(validator.errors.first('first_name')) // The first name field is required.\n```\n\nNote: by default all \\_ characters will be replaced with spaces.\n\n### Language Support\n\nError messages are in English by default. To include another language in the browser, reference the language file in a\nscript tag and call `Validator.useLang('lang_code')`.\n\n```html\n\u003cscript src=\"dist/main.js\"\u003e\u003c/script\u003e\n\u003cscript src=\"dist/lang/km.js\"\u003e\u003c/script\u003e\n\u003cscript\u003e\n  Validator.useLang('km')\n\u003c/script\u003e\n```\n\nIn Node, it will automatically pick up on the language source files.\n\n```js\nconst Validator = require('validatorjs')\n\nValidator.useLang('km')\n```\n\nIf you don't see support for your language, please add one to `src/lang`!\n\nYou can also add your own custom language by calling `setMessages`:\n\n```js\nValidator.setMessages('lang_code', {\n  required: 'The :attribute field is required.',\n})\n```\n\nGet the raw object of messages for the given language:\n\n```js\nValidator.getMessages('lang_code')\n```\n\nSwitch the default language used by the validator:\n\n```js\nValidator.useLang('lang_code')\n```\n\nGet the default language being used:\n\n```js\nValidator.getDefaultLang() // returns e.g. 'en'\n```\n\nOverride default messages for language:\n\n```js\nconst messages = Validator.getMessages('en')\nmessages.required = 'Whoops, :attribute field is required.'\nValidator.setMessages('en', messages)\n```\n\n### License\n\nCopyright \u0026copy; 2020-Present Chantouch Sek\n\nReleased under the MIT license\n\n### Credits\n\nValidatorJs re-written by Chantouch Sek\n\nE-Mail: [chantouchsek.cs83@gmail.com](mailto:chantouchsek.cs93@gmail.com)\n\nTwitter [@DevidCs83](https://twitter.com/DevidCs83)\n\nWebsite: [Chantouch](https://chantouch.me)\n","funding_links":["https://patreon.com/chantouch"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchantouchsek%2Fvalidatorjs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchantouchsek%2Fvalidatorjs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchantouchsek%2Fvalidatorjs/lists"}