{"id":25730859,"url":"https://github.com/skaterdav85/validatorjs","last_synced_at":"2025-02-26T02:01:54.447Z","repository":{"id":4585027,"uuid":"5727081","full_name":"mikeerickson/validatorjs","owner":"mikeerickson","description":"A data validation library in JavaScript for the browser and Node.js,  inspired by Laravel's Validator.","archived":false,"fork":false,"pushed_at":"2024-05-15T15:58:46.000Z","size":3530,"stargazers_count":1790,"open_issues_count":87,"forks_count":278,"subscribers_count":27,"default_branch":"master","last_synced_at":"2025-02-23T18:09:56.445Z","etag":null,"topics":["browser","client","javascript","laravel","node","nodejs","validation"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/validatorjs","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/mikeerickson.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":"2012-09-08T09:09:41.000Z","updated_at":"2025-02-23T14:32:51.000Z","dependencies_parsed_at":"2024-06-05T05:03:23.778Z","dependency_job_id":null,"html_url":"https://github.com/mikeerickson/validatorjs","commit_stats":{"total_commits":467,"total_committers":70,"mean_commits":6.671428571428572,"dds":0.7730192719486082,"last_synced_commit":"46928d706054b94821680c089de8b2a185830429"},"previous_names":["skaterdav85/validatorjs"],"tags_count":69,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikeerickson%2Fvalidatorjs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikeerickson%2Fvalidatorjs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikeerickson%2Fvalidatorjs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mikeerickson%2Fvalidatorjs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mikeerickson","download_url":"https://codeload.github.com/mikeerickson/validatorjs/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240777532,"owners_count":19855859,"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":["browser","client","javascript","laravel","node","nodejs","validation"],"created_at":"2025-02-26T02:01:36.941Z","updated_at":"2025-02-26T02:01:54.379Z","avatar_url":"https://github.com/mikeerickson.png","language":"JavaScript","readme":"# validatorjs\n\nThe validatorjs library makes data validation in JavaScript very easy in both the browser and Node.js.\nThis library was inspired by the [Laravel framework's Validator](http://laravel.com/docs/validation).\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\n## Installation\n\n### Using npm\n\n```bash\nnpm install validatorjs\n```\n\n### Using yarn\n\n```bash\nyarn add validatorjs\n```\n\n### Browser\n\n```html\n\u003cscript src=\"validator.js\"\u003e\u003c/script\u003e\n```\n\n### Node.js / Browserify\n\n```js\n// ES5\nlet Validator = require('validatorjs');\n```\n\n```js\n// ES6\nimport * as Validator from 'validatorjs';\n```\n\n### Basic Usage\n\n```js\nlet validation = new Validator(data, rules [, customErrorMessages]);\n```\n\n__data__ {Object} - The data you want to validate\n\n__rules__ {Object} - Validation rules\n\n__customErrorMessages__ {Object} - Optional custom error messages to return\n\n#### Example 1 - Passing Validation\n\n```js\nlet data = {\n  name: 'John',\n  email: 'johndoe@gmail.com',\n  age: 28\n};\n\nlet rules = {\n  name: 'required',\n  email: 'required|email',\n  age: 'min:18'\n};\n\nlet 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\nlet validation = new Validator({\n  name: 'D',\n  email: 'not an email address.com'\n}, {\n  name: 'size:3',\n  email: 'required|email'\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### Nested Rules\n\nNested objects can also be validated. There are two ways to declare validation rules for nested objects. The first way is to declare the validation rules with a corresponding nested object structure that reflects the data. The second way is to declare validation rules with flattened key names. For example, to validate the following data:\n\n```js\nlet data = {\n  name: 'John',\n  bio: {\n    age: 28,\n    education: {\n      primary: 'Elementary School',\n      secondary: 'Secondary School'\n    }\n  }\n};\n```\n\nWe could declare our validation rules as follows:\n\n```js\nlet nested = {\n  name: 'required',\n  bio: {\n    age: 'min:18',\n    education: {\n      primary: 'string',\n      secondary: 'string'\n    }\n  }\n};\n\n// OR\n\nlet flattened = {\n  'name': 'required',\n  'bio.age': 'min:18',\n  'bio.education.primary': 'string',\n  'bio.education.secondary': 'string'\n};\n```\n\n### WildCards Rules\n\nWildCards can also be validated.\n\n```js\nlet data = {\n  users: [{\n    name: 'John',\n    bio: {\n      age: 28,\n      education: {\n        primary: 'Elementary School',\n        secondary: 'Secondary School'\n      }\n    }\n  }]\n};\n```\n\nWe could declare our validation rules as follows:\n\n```js\nlet rules = {\n  'users.*.name': 'required',\n  'users.*.bio.age': 'min:18',\n  'users.*.bio.education.primary': 'string',\n  'users.*.bio.education.secondary': 'string'\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 validation. 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 unter 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 alpha-numeric characters, as well as dashes and underscores.\n\n#### alpha_num\n\nThe field under validation must be entirely alpha-numeric 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\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 the 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'`, `'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 password, 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 than the field under validation.\n\n#### email\n\nThe field under validation must be formatted as an e-mail address.\n\n#### hex\nThe field under validation should be a hexadecimal format. Useful in combination with other rules, like `hex|size:6` for hex 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#### min:value\n\nValidate that an attribute is at least a given size.\n\n_Note: Minimum checks are inclusive._\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#### present\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:anotherfield,value\n\nThe field under validation must be present and not empty if the anotherfield field is equal to any value.\n\n#### required_unless:anotherfield,value\n\nThe field under validation must be present and not empty unless the anotherfield 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 of 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 of the other specified fields are not present.\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 of 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 delimiters, especially if the regular expression contains a pipe character.\nFor each backward slash that you used in your regex pattern, you must escape each one with another backward slash.\n\n#### Example 3 - Regex validation\n\n```js\nlet validation = new Validator({\n  name: 'Doe',\n  salary: '10,000.00',\n  yearOfBirth: '1980'\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\nvalidation.fails(); // false\nvalidation.passes(); // true\n\n```\n\n#### Example 4 - Type Checking Validation\n\n```js\nlet validation = new Validator({\n  age: 30,\n  name: ''\n}, {\n  age: ['required', { 'in': [29, 30] }],\n  name: [{ required_if: ['age', 30] }]\n});\n\nvalidation.fails(); // true\nvalidation.passes(); // false\n\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 errorMessage will be replaced with the attribute name.\n\n```js\nValidator.register('telephone', function(value, requirement, attribute) { // requirement parameter defaults to null\n  return value.match(/^\\d{3}-\\d{3}-\\d{4}$/);\n}, 'The :attribute phone number is not in the format XXX-XXX-XXXX.');\n```\n\n### Asynchronous Validation\n\nRegister an asynchronous rule which accepts a `passes` callback:\n\n```js\nValidator.registerAsync('username_available', function(username, attribute, req, passes) {\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\nlet validator = new Validator({\n\tusername: 'test123'\n}, {\n\tusername: 'required|min:3|username_available'\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\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 for 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\nlet 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 third argument to the Validator object, just like with [Laravel](http://laravel.com/docs/validation#custom-error-messages).\n\n```js\nlet input = {\n  name: ''\n};\n\nlet rules = {\n  name : 'required'\n};\n\nlet validation = new Validator(input, rules, { required: 'You forgot to give a :attribute' });\nvalidation.passes();\nvalidation.errors.first('name'); // returns 'You forgot to give a name'\n```\n\nSome of the validators have string and numeric versions. You can change them too.\n\n```js\nlet input = {\n  username: 'myusernameistoolong'\n};\n\nlet rules = {\n  username : 'max:16'\n};\n\nlet 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\nlet input = { name: '', email: '' };\nlet rules = { name : 'required', email : 'required' };\n\nlet 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\nTo display a custom \"friendly\" attribute name in error messages, use `.setAttributeNames()`\n\n```js\nlet 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```\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(function(attribute) {\n  return attribute.replace(/_/g, ' ');\n});\n\n// Or configure formatter for particular instance.\nlet validator = new Validator({ first_name: '' }, { first_name: 'required' });\nvalidator.setAttributeFormatter(function(attribute) {\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```\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 script tag and call `Validator.useLang('lang_code')`.\n\n```html\n\u003cscript src=\"dist/validator.js\"\u003e\u003c/script\u003e\n\u003cscript src=\"dist/lang/ru.js\"\u003e\u003c/script\u003e\n\u003cscript\u003e\n  Validator.useLang('es');\n\u003c/script\u003e\n```\n\nIn Node, it will automatically pickup on the language source files.\n\n```js\nlet Validator = require('validatorjs');\nValidator.useLang('ru');\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\nlet messages = Validator.getMessages('en');\nmessages.required = 'Whoops, :attribute field is required.';\nValidator.setMessages('en', messages);\n```\n\n### License\n\nCopyright \u0026copy; 2012-2019 David Tang\nReleased under the MIT license\n\n### Credits\n\nvalidatorjs created by David Tang\nvalidatorjs maintained by Mike Erickson and Contributors\n\nE-Mail: [codedungeon@gmail.com](mailto:codedungeon@gmail.com)\n\nTwitter: [@codedungeon](http://twitter.com/codedungeon)\n\nWebsite: [codedungeon.io](http://codedungeon.io)\n","funding_links":[],"categories":["Packages"],"sub_categories":["Validator"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fskaterdav85%2Fvalidatorjs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fskaterdav85%2Fvalidatorjs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fskaterdav85%2Fvalidatorjs/lists"}