{"id":13671394,"url":"https://github.com/fabioricali/valify","last_synced_at":"2025-04-10T18:21:00.914Z","repository":{"id":57390454,"uuid":"103382560","full_name":"fabioricali/valify","owner":"fabioricali","description":"Validates data in JavaScript in a very simple way","archived":false,"fork":false,"pushed_at":"2020-09-03T14:44:55.000Z","size":282,"stargazers_count":13,"open_issues_count":1,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-04-26T11:20:22.877Z","etag":null,"topics":["struct","structured-data","types","validation","validation-library"],"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/fabioricali.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","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-09-13T09:49:11.000Z","updated_at":"2020-09-03T14:44:57.000Z","dependencies_parsed_at":"2022-09-26T16:51:18.371Z","dependency_job_id":null,"html_url":"https://github.com/fabioricali/valify","commit_stats":null,"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fabioricali%2Fvalify","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fabioricali%2Fvalify/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fabioricali%2Fvalify/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fabioricali%2Fvalify/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fabioricali","download_url":"https://codeload.github.com/fabioricali/valify/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248270477,"owners_count":21075794,"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":["struct","structured-data","types","validation","validation-library"],"created_at":"2024-08-02T09:01:08.457Z","updated_at":"2025-04-10T18:21:00.886Z","avatar_url":"https://github.com/fabioricali.png","language":"JavaScript","readme":"\u003cdiv align=\"center\"\u003e\n\u003cbr/\u003e\u003cbr/\u003e\n\u003cimg width=\"220\" src=\"https://raw.githubusercontent.com/fabioricali/valify/master/extra/logo-valify.png\" title=\"Valify\"/\u003e\n\u003cbr/\u003e\nValidates data to easy way in JavaScript.\n\u003cbr/\u003e\u003cbr/\u003e\u003cbr/\u003e\n\u003ca href=\"https://travis-ci.org/fabioricali/valify\" target=\"_blank\"\u003e\u003cimg src=\"https://travis-ci.org/fabioricali/valify.svg?branch=master\" title=\"Build Status\"/\u003e\u003c/a\u003e\n\u003ca href=\"https://opensource.org/licenses/MIT\" target=\"_blank\"\u003e\u003cimg src=\"https://img.shields.io/badge/License-MIT-yellow.svg\" title=\"License: MIT\"/\u003e\u003c/a\u003e\n\u003cbr/\u003e\u003cbr/\u003e\u003cbr/\u003e\n\u003c/div\u003e\n\nValify was created to easily validate data structures. With a simple syntax it is ideal in many contexts for example in REST API\n\n**Documentation**\n- [Installation](#installation)\n    - [Browser](#browser)\n- [Basic usage](#basic-usage)\n- [Model options](#model-options)\n- [Field options](#field-options)\n- [Error object](#error-object)\n- [Default values](#default-values)\n- [Nested models](#nested-models)\n- [Promises](#using-promise)\n- [Detect unknown fields](#detect-unknown-fields)\n- [Auto cast](#auto-cast)\n- [Manipulate data](#manipulate-data)\n- [Immutability](#immutability)\n- [Undefined values](#undefined-values)\n- [Define custom types](#define-custom-type)\n    - [Use multiple rules together](#use-multiple-rules-together)\n    - [Arguments](#arguments-in-custom-type)\n- [Locale](#locale)\n- [Types](#available-types)\n- [Upgrade to V4](#upgrade-to-v4)\n\n### Installation\n```\nnpm install --save valify\n```\n\n#### Browser\n```html\n\u003cscript src=\"https://unpkg.com/valify/dist/valify.min.js\"\u003e\u003c/script\u003e\n```\n\n### Basic usage\n```javascript\nconst Valify = require('valify');\n\n// Define a model\nconst userModel = new Valify({\n    firstName: 'string',\n    lastName: 'string',\n    age: 'int?', // this is not required\n    role: {\n        type: 'string',\n        default: 'editor'\n    },\n    colors: ['string'],\n    createdAt: {\n        type: 'date',\n        default: new Date()\n    }\n});\n\n// A data object\nconst data = {\n    firstName: 'Mike',\n    lastName: 'Ricali',\n    role: 'owner',\n    colors: ['red', 'yellow', 'orange']\n};\n\n// Validate userModel\ntry {\n    userModel(data);\n} catch(e) {\n    console.log(e.message, e.fields);\n}\n```\n\n### Model options\n|Property|Type|Default|Description|\n|-|-|-|-|\n|`usePromise`|`boolean`|`false`|If you need to use with Promise must just add usePromise to model settings. [Details](#using-promise)|\n|`detectUnknown`|`boolean`|`false`|If you need to define a strict model where all the fields correspond to those defined, you can set detectUnknown to true. [Details](#detect-unknown-fields)|\n|`autoCast`|`boolean`|`false`|Sometimes you may need to cast a string (where possible) to a primitive type. You can set autoCast to true. [Details](#auto-cast)|\n|`returnImmutable`|`boolean`|`false`|Valify model returns also the data that you have passed for the validation, if you want an immutable data, set returnImmutable to true. [Details](#immutability)|\n|`overwriteUndefined`|`boolean`|`false`|If you need manage undefined value with a default value, set overwriteUndefined to true, obviously works only if default is set. [Details](#undefined-values)|\n|`appendToError`|`object`|{}|If you need to add custom properties to error stack|\n\n### Field options\n|Property|Type|Default|Description|\n|-|-|-|-|\n|`type`|`object`,`array`,`string`,`function`|`null`|Type of control|\n|`required`|`boolean`|`true`|Indicates if the field is required|\n|`default`|`any`|`null`|Default value|\n|`allowNull`|`boolean`|`false`|Allow null value, overwrites all checks|\n|`allowEmpty`|`boolean`|`true`|Allow empty value, works for `string`, `array` and `object`|\n|`locale`|`object`|`object`|An object that contains locale strings that overwrites those globals|\n|`convert`|`function`|`null`|A function to manipulate/conversion data|\n|`onError`|`function`|`null`|A function triggered when an check fails|\n\n### Error object\nValify in case of errors returns an object with 2 properties:\n- `message` is the first error occurred\n- `fields` is an array of all errors occurred\n\n```\n{\n    message: '\"aParam.other.lastName\" is required',\n    fields: [\n        {\n            path: 'aParam.other.lastName', \n            message: '\"aParam.other.lastName\" is required', \n            field: 'lastName',\n            type: 'string'\n        }\n    ]\n}\n```\n\n### Default values\nYou can set a default value for each field, this setting overwrites `required` property to `false`.\n\n```javascript\nconst Valify = require('valify');\n\n// Define a model\nconst userModel = new Valify({\n    name: 'string',\n    role: {\n        type: 'string',\n        default: 'editor'\n    }\n});\n\n// A data object\nconst data = {\n    name: 'Mike Ricali'\n};\n\ntry {\n    userModel(data); //=\u003e {name: 'Mike Ricali'}\n} catch(e) {\n    console.log(e.message, e.fields);\n}\n```\n\n### Nested models\nIt's possible also add nested model, for example you could have an array field like below:\n\n```javascript\n\nconst userModel = new Valify({\n    firstName: 'string',\n    lastName: 'string',\n    records: [\n        new Valify({\n            id: 'int',\n            accessOn: 'date',\n            otherNested: new Valify({\n                color: 'string'\n            })\n        })\n    ]\n});\n\n// A data object\nconst data = {\n    firstName: 'Mike',\n    lastName: 'Ricali',\n    records: [\n        {\n            id: 1,\n            accessOn: '2017-12-23T00:01:00',\n            otherNested: {\n                color: 'red'\n            }\n        },\n        {\n            id: 2,\n            accessOn: '2017-12-23T00:02:00',\n            otherNested: {\n                color: 'yellow'\n            }\n        },\n        {\n            id: 3,\n            accessOn: '2017-12-23T00:03:00',\n            otherNested: {\n                color: 'green'\n            }\n        }\n    ]\n};\n\n// Validate userModel\ntry {\n    userModel(data);\n} catch(e) {\n    console.log(e.message, e.fields);\n}\n```\n\n### Using promise\nIf you need to use with Promise must just add `usePromise` to model settings.\n\n```javascript\n\n// Define a model\nconst userModel = new Valify({\n    firstName: {\n        type: 'string',\n        required: true\n    },\n    lastName: {\n        type: 'string',\n        required: true\n    }\n}, {\n    usePromise: true\n});\n\n// A data object\nconst data = {\n    firstName: 'Mike'\n};\n\n// Validate userModel\nuserModel(data).then(()=\u003e{\n    console.log('ok');\n}).catch(e =\u003e {\n    console.log(e);\n    // An object like below\n    /*\n        {\n            message: 'lastName is required',\n            fields: [{field: 'lastName', message: 'lastName is required', path: 'lastName'}]\n        }\n     */\n});\n\n```\n\n### Detect unknown fields\nIf you need to define a strict model where all the fields correspond to those defined, you can set `detectUnknown` to true.\n\n```javascript\n\nconst userModel = new Valify({\n    firstName: 'string',\n    lastName: 'string',\n    email: 'email'\n}, {\n    detectUnknown: true\n});\n\ntry {\n    userModel({\n        firstName: 'Mike',\n        lastName: 'Storm',\n        email: 'test@test.net',\n        role: 'admin',\n        age: 26,\n    })\n} catch (e) {\n    console.log(e.message); //Unknown fields were detected: role, age\n}\n\n```\n\n### Auto cast\nSometimes you may need to cast a string (where possible) to a primitive type. You can set `autoCast` to true.\n\n```javascript\n\nconst userModel = new Valify({\n    firstName: 'string',\n    lastName: 'string',\n    email: 'email',\n    aBoolean: 'boolean',\n    aNumber: 'number',\n    aUndefined: 'undefined',\n    aNull: 'null'\n}, {\n    autoCast: true\n});\n\ntry {\n    userModel({\n        firstName: 'Mike',\n        lastName: 'Storm',\n        email: 'test@test.net',\n        role: 'admin',\n        aBoolean: 'true',\n        aNumber: '52',\n        aUndefined: 'undefined',\n        aNull: 'null'\n    })\n    //... done\n} catch (e) {\n    \n}\n\n```\n\n### Manipulate data\nYou may need to manipulate data before the validation.\n\n```javascript\n// Define a model\nconst userModel = new Valify({\n    firstName: {\n        type: 'string',\n        convert: value =\u003e value.toUpperCase()\n    },\n    lastName: {\n        type: 'string',\n        convert: value =\u003e value.toUpperCase()\n    },\n    age: {\n        type: 'number',\n        convert: value =\u003e parseInt(value)\n    }\n});\n\n// A data object\nconst data = {\n    firstName: 'Mike',\n    lastName: 'Ricali',\n    age: '25'\n};\n\nuserModel(data);\n\nconsole.log(data.firstName, data.lastName, data.age, typeof data.age); //=\u003e MIKE RICALI 25 number\n```\n\n- Convert function returns: \n    - `value`, current value\n    - `data`, a copy of origin data object\n    - `be`, a library used for several validations. More info on \u003ca href=\"https://be.js.org/docs.html\"\u003e\u003cstrong\u003ebeJS\u003c/strong\u003e\u003c/a\u003e\n    \n\n### Immutability\nValify model returns also the data that you have passed for the validation, if you want an immutable data, set `returnImmutable` to true.\n```javascript\nconst userModel = new Valify({\n    firstName: 'string',\n    lastName: {\n        type: 'string',\n        convert: value =\u003e value.toUpperCase()\n    },\n    email: 'email'\n}, {returnImmutable: true});\n\nconst data = {\n    firstName: 'Mike',\n    lastName: 'Storm',\n    email: 'test@test.net'\n};\n\nconst newData = userModel(data);\n\nconsole.log(data.lastName, newData.lastName);\n//=\u003e Storm, STORM\n```\n\n### Undefined values\nIf you need manage undefined value with a default value, set `overwriteUndefined` to true, obviously works only if `default` is set.\n```javascript\nconst userModel = new Valify({\n    aNumber: 'int',\n    lastName: {\n        type: 'string',\n        default: 'Mike'\n    }\n},{\n    overwriteUndefined: true\n});\n\nconst a = ['hello'];\n\ntry {\n    userModel({\n        aNumber: 24,\n        lastName: a[1] //=\u003e index at 1 is undefined but will be applied default value \"mike\"\n    });\n    done();\n} catch (e) {}\n```\n\n### Define custom type\nThere are different ways to define custom types:\n\n##### 1) Globally, using static method `addType` or `addTypes` if you want add more than one type\n```javascript\n\nValify.addType('mycustom1', (value, data) =\u003e {\n    console.log(data);\n    return value === 10;\n});\n\n// it's also possible returns a string as error like below\nValify.addType('mycustom2', (value) =\u003e {\n    if (value !== 10)\n        return 'ops... must be 10'\n});\n\n// One method to add several types\nValify.addTypes([\n    {\n        name: 'mycustom3',\n        fn: value =\u003e value === 'hello'\n    },\n    {\n        name: 'mycustom4',\n        fn: value =\u003e value === 'world'\n    }\n]);\n\n// Define a model\nconst userModel = new Valify({\n    aNumber: 'mycustom1',\n    otherNumber: 'mycustom2'\n});\n\n// A data object\nconst data = {\n    aNumber: 9,\n    otherNumber: 11,\n};\n\ntry {\n    userModel(data);\n} catch(e) {\n    console.log(e.message, e.fields);\n} \n```\n\n##### 2) Local, passing a function to `type` param\n```javascript\n\n// Define a model\nconst userModel = new Valify({\n    aString: {\n        type: value =\u003e typeof value === 'string'\n    },\n    // or \n    aBoolean: value =\u003e typeof value === 'boolean'\n});\n\n// A data object\nconst data = {\n    aString: 'hello',\n    aBoolean: 5\n};\n\ntry {\n    userModel(data);\n} catch(e) {\n    console.log(e.message, e.fields);\n} \n```\n\n#### Use multiple rules together\nIf you need to define multiple checks in one type, you can do this:\n\n```javascript\nnew Valify({\n    myString: value =\u003e {\n        if (typeof value !== 'string')\n            return 'must be a string';\n        if (value.length \u003c 5)\n            return 'must be greater than 5 chars';\n        if (value.length \u003e 10)\n            return 'must be less than 10 chars';\n    }\n})\n```  \n\n#### Arguments in custom type\n- Inside all custom type function are passed 3 arguments: \n    - `value`, current value\n    - `data`, a copy of origin data object\n    - `be`, a library used for several validations. More info on \u003ca href=\"https://be.js.org/docs.html\"\u003e\u003cstrong\u003ebeJS\u003c/strong\u003e\u003c/a\u003e\n    \nExample\n\n```javascript\nnew Valify({\n    color0: 'string',\n    color1: (value, data, be) =\u003e {\n        if (!be.string(value))\n            return 'must be a string';\n        if (value === data.color0)\n            return 'must be different of color0';\n    }\n})\n```  \n\n### Locale\nYou can set locale string in two ways:\n\n##### 1) Globally, using static method `setLocale`\n```javascript\n\nValify.setLocale({\n    TYPE_FAIL: 'this type has failed'\n});\n\n```\n\n**Default strings**\n\n|Name|Default|\n|-|-|\n|`UNKNOWN_TYPE`|`Unknown type: \"{type}\"`|\n|`TYPE_FAIL`|`\"{path}\" expects \"{type}\" but receives: {dataField}`|\n|`TYPE_ARRAY_FAIL`|`\"{path}\" expects array of \"{type}\" but receives: {dataField}`|\n|`TYPE_FUNCTION_FAIL`|`\"{path}\" receives: {dataField}`|\n|`FIELD_REQUIRED`|`\"{path}\" is required`|\n|`DATA_REQUIRED`|`Data is required and must be an object`|\n|`FIELD_CANNOT_EMPTY`|`\"{path}\" cannot be empty`|\n|`UNKNOWN_DETECTED`|`Unknown fields were detected: {unknown}`|\n\n##### 2) Local, into field settings\n```javascript\n\n// Define a model\nconst userModel = new Valify({\n    aString: {\n        type: 'string',\n        locale: {\n            TYPE_FAIL: 'this type has failed'\n        }\n    }\n});\n\n```\n\n- There are only two available properties:\n    - **`TYPE_FAIL`**\n    - **`TYPE_ARRAY_FAIL`**\n    - **`FIELD_REQUIRED`**\n    - **`FIELD_CANNOT_EMPTY`**\n\n### Available types\n\nAll types that you can use:\n\n- JavaScript standard\n    - `arguments`\n    - `array`\n    - `boolean`\n    - `buffer`\n    - `date`\n    - `error`\n    - `float32array`\n    - `float64array`\n    - `function`\n    - `generatorfunction`\n    - `int16array`\n    - `int32array`\n    - `int8array`\n    - `map`\n    - `null`\n    - `number`\n    - `object`\n    - `promise`\n    - `regexp`\n    - `set`\n    - `string`\n    - `symbol`\n    - `uint16array`\n    - `uint32array`\n    - `uint8array`\n    - `uint8clampedarray`\n    - `undefined`\n    - `weakmap`\n    - `weakset`\n    \n- Extra    \n    - `alpha`\n    - `alphanumeric`\n    - `any`\n    - `datestring`\n    - `email`\n    - `float`\n    - `int`\n    - `ip`\n    - `timestring`\n    - `uuid`\n    - `url`\n\n### Upgrade to V4\n- **Breaking changes**\n    - **Changed** in locale strings {field} with {path}\n    - **Changed** `convert` position, now is before all checks\n    - **Removed** validators, use custom types instead\n\n## Changelog\nYou can view the changelog \u003ca target=\"_blank\" href=\"https://github.com/fabioricali/Valify/blob/master/CHANGELOG.md\"\u003ehere\u003c/a\u003e\n\n## License\nValify is open-sourced software licensed under the \u003ca target=\"_blank\" href=\"http://opensource.org/licenses/MIT\"\u003eMIT license\u003c/a\u003e\n\n## Author\n\u003ca target=\"_blank\" href=\"http://rica.li\"\u003eFabio Ricali\u003c/a\u003e","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffabioricali%2Fvalify","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffabioricali%2Fvalify","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffabioricali%2Fvalify/lists"}