├── .circleci └── config.yml ├── .github └── dependabot.yml ├── .gitignore ├── .npmignore ├── .vscode └── settings.json ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── rollup.config.js ├── src └── index.ts ├── test └── index.test.ts └── tsconfig.json /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | with_node10: &with_node10 4 | docker: 5 | - image: node:10 6 | environment: 7 | NODE_VERSION: 10 8 | steps: 9 | - checkout 10 | 11 | - restore_cache: 12 | keys: 13 | - npm-{{ checksum "package-lock.json" }}-{{ .Environment.NODE_VERSION }}-v1 14 | - npm- 15 | 16 | - run: 17 | name: Install NPM modules 18 | command: npm install 19 | 20 | - run: 21 | name: Build module 22 | command: npm run build 23 | 24 | - run: 25 | name: Run test 26 | command: npm run test 27 | 28 | - save_cache: 29 | key: npm-{{ checksum "package-lock.json" }}-{{ .Environment.NODE_VERSION }}-v1 30 | paths: 31 | - ~/node_modules 32 | 33 | with_node12: 34 | <<: *with_node10 35 | docker: 36 | - image: node:12 37 | environment: 38 | NODE_VERSION: 12 39 | 40 | workflows: 41 | version: 2 42 | build_and_test: 43 | jobs: 44 | - with_node10 45 | - with_node12 46 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: '01:00' 8 | timezone: America/Los_Angeles 9 | assignees: 10 | - kengogo 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | dist/ 3 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src 2 | test 3 | tsconfig.json 4 | rollup.config.js 5 | .vscode 6 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "node_modules/typescript/lib" 3 | } -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at open-source@indiegogo.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Indiegogo, Kengo Hamasaki 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vuex-module-validatable-state 2 | 3 | [![npm](https://img.shields.io/npm/v/vuex-module-validatable-state.svg?style=for-the-badge)](https://www.npmjs.com/package/vuex-module-validatable-state) 4 | [![CircleCI](https://img.shields.io/circleci/project/github/indiegogo/vuex-module-validatable-state/master.svg?style=for-the-badge)](https://circleci.com/gh/indiegogo/vuex-module-validatable-state) 5 | 6 | Simple Vuex module to handle form fields and validations. 7 | 8 | ![190611_module](https://user-images.githubusercontent.com/85887/59253812-dcd08180-8be3-11e9-922d-c5c6e6a2e777.gif) 9 | 10 | You can build a view model for your form, which runs valdations easily. You just provide initial fields and validators to build the module, then map getters/actions to components. 11 | 12 | Play in [this sandbox](https://o46g3.codesandbox.io/). 13 | 14 | ## Usage 15 | 16 | ### Installation 17 | 18 | ``` 19 | $ npm i vuex-module-validatable-state 20 | ``` 21 | 22 | ### Register to core Vuex module 23 | 24 | This module provides the function to return Vuex module as default. The function takes arguments: 25 | 26 | - Initial field set 27 | - Validators 28 | 29 |
30 | A. Define directly 31 | 32 | ```ts 33 | import validatableModule from "vuex-module-validatable-state"; 34 | 35 | const initialFields = { 36 | amount: null, 37 | description: "default text" 38 | }; 39 | 40 | const validators = { 41 | amount: [ 42 | ({ amount }) => amount === null ? "Require this" : false 43 | ], 44 | description: [ 45 | ({ description }) => description.length > 15 ? "Should be shorter than 15" : false, 46 | ({ description, amount }) => description.indexOf(amount.toString()) ? "Should include amount" : false, 47 | ] 48 | }; 49 | 50 | new Vuex.Store({ 51 | modules: { 52 | myForm: { 53 | namespaced: true 54 | store, 55 | getters, 56 | actions, 57 | mutations, 58 | modules: { 59 | ...validatableModule(initialFields, validators) // <-- HERE 60 | } 61 | } 62 | } 63 | }); 64 | ``` 65 |
66 | 67 |
68 | B. Register to existing module 69 | 70 | ```ts 71 | import { register } from "vuex-module-validatable-state"; 72 | 73 | const initialFields = { 74 | amount: null, 75 | description: "default text" 76 | }; 77 | 78 | const validators = { 79 | amount: [ 80 | ({ amount }) => amount === null ? "Require this" : false 81 | ], 82 | description: [ 83 | ({ description }) => description.length > 15 ? "Should be shorter than 15" : false, 84 | ({ description, amount }) => description.indexOf(amount.toString()) ? "Should include amount" : false, 85 | ] 86 | }; 87 | 88 | const store = new Vuex.Store({ 89 | modules: { 90 | myForm: { 91 | namespaced: true 92 | store, 93 | getters, 94 | actions, 95 | mutations 96 | } 97 | } 98 | }); 99 | 100 | register(store, "myForm", initialFields, validators); 101 | ``` 102 |
103 | 104 | ### Map to Components 105 | 106 | #### Provided Getters 107 | 108 | |**Getter name**|**Returns**| 109 | ---|--- 110 | |`GetterTypes.ALL_FIELDS_VALID`|`boolean` whether all fields don't have error| 111 | |`GetterTypes.FIELD_VALUES`|All fields as `{ [fieldName]: value }`| 112 | |`GetterTypes.FIELD_ERRORS`|All errors as `{ [fieldName]: errorMessage }`| 113 | |`GetterTypes.FIELD_EDITABILITIES`|All editable flags as `{ [fieldName]: editability }`| 114 | |`GetterTypes.FIELD_DIRTINESSES`|All dirtiness flags as `{ [fieldName]: dirtiness }`| 115 | |`GetterTypes.ANY_FIELD_CHANGED`|`boolean` whether all fields are not dirty| 116 | 117 | #### Provided Actions 118 | 119 | Import `ActionTypes` from the module. 120 | 121 | |**Action name**|**Runs**| 122 | ---|--- 123 | |`ActionTypes.SET_FIELD`|Set value for a field, then runs validation if enabled| 124 | |`ActionTypes.SET_FIELDS_BULK`|Set values for fields at once, then make all dirtiness flags false| 125 | |`ActionTypes.RESET_FIELDS`|Reset values on field with initial values| 126 | |`ActionTypes.ENABLE_VALIDATION`|Enable interactive validation for a specific field, and run validations on this field immediately| 127 | |`ActionTypes.ENABLE_ALL_VALIDATIONS`|Enable interactive validations for all fields and run all validations immediately| 128 | |`ActionTypes.VALIDATE_FIELDS`|Validate for each field that is enabled for interactive validation| 129 | |`ActionTypes.SET_FIELDS_EDITABILITY`|Set editability flag for a field, disabled field is not updated nor validated| 130 | |`ActionTypes.SET_FIELDS_PRISTINE`|Make all dirtiness flags false| 131 | 132 | ### Validators 133 | 134 | You can pass validators when you initialize the module. 135 | 136 | ```ts 137 | const validators = { 138 | amount: [/* validators for filling error against to amount */], 139 | description: [/* validators for filling error against to description */] 140 | } 141 | ``` 142 | 143 | Each validator can take all fields values to run validation: 144 | 145 | ```ts 146 | const validators = { 147 | amount: [ 148 | ({ amount, description }) => /* return false or errorMessage */ 149 | ] 150 | } 151 | ``` 152 | 153 | Optionally, can take getters on the store which calls this module: 154 | 155 | ```ts 156 | const validators = { 157 | description: [ 158 | ({ description }, getters) => getters.getterOnStore && validationLogicIfGetterOnStoreIsTruthy(description) 159 | ] 160 | } 161 | ``` 162 | 163 | And you can request "interactive validation" which valites every time `dispatch(ActionTypes.SET_FIELD)` is called 164 | 165 | ```ts 166 | const validators = { 167 | amount: [ 168 | [({ amount }, getters) => /* validator logic */, { instant: true }] 169 | ] 170 | } 171 | ``` 172 | 173 | ### Provided Typings 174 | 175 | You can import handy type/interface definitions from the module. 176 | The generic `T` in below expects fields type like: 177 | 178 | ```ts 179 | interface FieldValues { 180 | amount: number; 181 | description: string; 182 | } 183 | ``` 184 | 185 | `getters[GetterTypes.FIELD_VALUES]` returns values with following `FieldValues` interface. 186 | 187 |
188 | See all typings 189 | 190 | #### `ValidatorTree` 191 | 192 | As like ActionTree, MutationTree, you can receive type guards for Validators. By giving your fields' type for Generics, validator can get more guards for each fields: 193 | 194 | ![image](https://user-images.githubusercontent.com/21182617/53462133-a174c300-39f7-11e9-9b73-a16e6f064193.png) 195 | 196 | #### `SetFieldAction` 197 | 198 | It's the type definition of the payload for dispatching `ActionTypes.SET_FIELD`, you can get type guard for your fields by giving Generics. 199 | 200 | ![image](https://user-images.githubusercontent.com/21182617/53462201-dd0f8d00-39f7-11e9-81f8-a927a96c75b4.png) 201 | 202 | #### `FieldValidationErrors` 203 | 204 | Type for `getters[GetterTypes.FIELD_ERRORS]` 205 | 206 | #### `FieldEditabilities` 207 | 208 | Type for `getters[GetterTypes.FIELD_EDITABILITIES]` 209 | 210 | #### `FieldDirtinesses` 211 | 212 | Type for `getters[GetterTypes.FIELD_DIRTINESSES]` 213 | 214 |
215 | 216 | ## Working Sample 217 | 218 | [![Edit Sample: vuex-module-validatable-state](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/vue-template-o46g3?fontsize=14) 219 | 220 | ### Registering to Vuex Store 221 | 222 | ```js 223 | const initialField = { 224 | amount: 0, 225 | description: null 226 | }; 227 | 228 | const validators = { 229 | amount: [ 230 | ({ amount }) => (!amount ? "Amount is required" : false), 231 | ({ amount }) => (amount <= 0 ? "Amount should be greater than 0" : false) 232 | ], 233 | description: [ 234 | ({ amount, description }) => 235 | amount > 1000 && !description 236 | ? "Description is required if amount is high" 237 | : false 238 | ] 239 | }; 240 | 241 | const store = new Vuex.Store({ 242 | modules: { 243 | ...theModule(initialField, validators) 244 | } 245 | }); 246 | ``` 247 | 248 | ### Mapping to Component 249 | 250 | ```vue 251 |