├── .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 | [](https://www.npmjs.com/package/vuex-module-validatable-state) 4 | [](https://circleci.com/gh/indiegogo/vuex-module-validatable-state) 5 | 6 | Simple Vuex module to handle form fields and validations. 7 | 8 |  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 |  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 |  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 | [](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 | 252 | 253 | 254 | Amount (Required, Positive) 255 | 256 | {{ errors.amount }} 257 | 258 | 259 | Description (Required if amount is greater than 1000) 260 | 261 | {{ errors.description }} 262 | 263 | Validate and Submit 264 | 265 | 266 | 267 | 311 | ``` 312 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vuex-module-validatable-state", 3 | "version": "0.5.0", 4 | "description": "Simple Vuex module to validate state for handling form", 5 | "main": "./dist/index.js", 6 | "typings": "./dist/index.d.ts", 7 | "files": [ 8 | "dist" 9 | ], 10 | "scripts": { 11 | "build": "rollup -c", 12 | "test": "jest" 13 | }, 14 | "repository": { 15 | "type": "git", 16 | "url": "git+ssh://git@github.com/indiegogo/vuex-module-validatable-state.git" 17 | }, 18 | "keywords": [ 19 | "vuex", 20 | "vue", 21 | "validation" 22 | ], 23 | "author": "Kengo Hamasaki ", 24 | "license": "MIT", 25 | "bugs": { 26 | "url": "https://github.com/indiegogo/vuex-module-validatable-state/issues" 27 | }, 28 | "homepage": "https://github.com/indiegogo/vuex-module-validatable-state#readme", 29 | "dependencies": {}, 30 | "devDependencies": { 31 | "@types/jest": "25.2.3", 32 | "jest": "25.5.4", 33 | "rollup": "1.31.1", 34 | "rollup-plugin-typescript2": "0.29.0", 35 | "ts-jest": "25.5.1", 36 | "typescript": "3.9.7", 37 | "vue": "2.6.12", 38 | "vuex": "3.6.0" 39 | }, 40 | "jest": { 41 | "preset": "ts-jest" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import typescript from 'rollup-plugin-typescript2'; 2 | import pkg from "./package.json"; 3 | 4 | export default { 5 | input: "./src/index.ts", 6 | plugins: [ 7 | typescript({ 8 | clean: true, 9 | useTsconfigDeclarationDir: true 10 | }) 11 | ], 12 | output: { 13 | file: pkg.main, 14 | format: "cjs", 15 | exports: "named" 16 | }, 17 | external: ["vuex"] 18 | } 19 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { ActionTree, GetterTree, MutationTree, Store, ModuleTree } from "vuex"; 2 | 3 | interface FormField { 4 | value: T; 5 | error: string | false; 6 | disabled: boolean; 7 | dirty: boolean; 8 | validationEnabled: boolean; 9 | } 10 | 11 | const initialStateOfField = (initialValue: T): FormField => ({ 12 | value: initialValue, 13 | error: false, 14 | disabled: false, 15 | dirty: false, 16 | validationEnabled: false 17 | }); 18 | 19 | interface ValidatableFieldsState { 20 | validatableState: { 21 | [K in keyof T]: FormField; 22 | }; 23 | }; 24 | 25 | type ValidationResult = false | string; 26 | interface ValidationOption { instant: boolean; } 27 | 28 | // In the consumer's end, [() => "error message", { instant: true; }] is inferred as (string | { instant: true })[] 29 | // So that doesn't match ValidatorWithOption's type: [() => ValidationResult, ValidationOption] 30 | // https://github.com/Microsoft/TypeScript/issues/16656 31 | // type Validator = (ValidatorWithoutOption | ValidatorWithOption); 32 | // type ValidatorWithoutOption = (fields: Partial, getters?) => ValidationResult; 33 | // type ValidatorWithOption = () => [(fields: Partial) => ValidationResult, ValidationOption]; 34 | export type Validator = (fields?: Partial, getters?) => ValidationResult | [(fields?: Partial, getters?) => ValidationResult, ValidationOption]; 35 | 36 | export type ValidatorTree = { 37 | [key in keyof T]?: Validator[]; 38 | }; 39 | 40 | export type FieldValidationErrors = { 41 | [key in keyof F]: ValidationResult; 42 | }; 43 | 44 | export type FieldEditabilities = { 45 | [key in keyof F]: boolean; 46 | }; 47 | 48 | export type FieldDirtinesses = { 49 | [key in keyof F]: boolean; 50 | }; 51 | 52 | export type SetFieldAction = (payload: { name: T ; value: F[T]; }) => void; 53 | export type EnableValidationAction = (payload: T) => void; 54 | 55 | export enum GetterTypes { 56 | ALL_FIELDS_VALID = "validatableStateAllFieldsValid", 57 | ANY_FIELD_CHANGED = "validatableStateAnyFieldChanged", 58 | FIELD_VALUES = "validatableStateFieldValues", 59 | FIELD_ERRORS = "validatableStateFieldErrors", 60 | FIELD_EDITABILITIES = "validatableStateFieldEditabilities", 61 | FIELD_DIRTINESSES = "validatableStateFieldDirtinesses" 62 | } 63 | 64 | enum MutationTypes { 65 | INITIALIZE_FIELDS = "INITIALIZE_FIELDS", 66 | SET_FIELD_VALUE = "SET_FIELD_VALUE", 67 | SET_FIELD_ERROR = "SET_FIELD_ERROR", 68 | SET_FIELD_EDITABILITY = "SET_FIELD_EDITABILITY", 69 | SET_FIELD_EDITABILITIES_BULK = "SET_FIELD_EDITABILITIES_BULK", 70 | SET_FIELD_DIRTINESS = "SET_FIELD_DIRTINESS", 71 | ENABLE_VALIDATION = "ENABLE_VALIDATION", 72 | ENABLE_ALL_VALIDATIONS = "ENABLE_ALL_VALIDATIONS", 73 | SET_FIELDS_PRISTINE = "SET_FIELDS_PRISTINE" 74 | } 75 | 76 | export enum ActionTypes { 77 | SET_FIELD_VALUE = "validatableStateSetFieldValue", 78 | SET_FIELD_EDITABILITY = "validatableStateSetFieldEditability", 79 | SET_FIELDS_BULK = "validatableStateSetFieldsBulk", 80 | SET_FIELD_EDITABILITIES_BULK = "validatableStateSetFieldEditabilitiesBulk", 81 | RESET_FIELDS = "validatableStateResetFields", 82 | VALIDATE_FIELDS = "validatableStateValidateFields", 83 | ENABLE_VALIDATION = "validatableStateEnableValidation", 84 | ENABLE_ALL_VALIDATIONS = "validatableStateEnableAllValidations", 85 | SET_FIELDS_PRISTINE = "validatableStateSetFieldsPristine" 86 | } 87 | interface InternalState { 88 | fields: ValidatableFieldsState["validatableState"]; 89 | } 90 | 91 | /** 92 | * Function returns Vuex module to provide validatable field lifecycle 93 | * @param initialFields - Field names with initial variable 94 | * @param validators - Validators for each field 95 | * @example 96 | * buildModule( 97 | * { name: null, age: null }, 98 | * { 99 | * name: [ 100 | * ({ name }) => name && name.length > 2 101 | * ], 102 | * age: [ 103 | * ({ age }) => age && age > 0 104 | * ] 105 | * } 106 | * ) 107 | */ 108 | const buildModule = ( 109 | initialFields: F, 110 | validators: ValidatorTree 111 | ): ModuleTree => { 112 | const stateFields = { fields: {} } as InternalState; // fields is not fulfilling the actual type... 113 | (Object.entries(initialFields) as [keyof F, F[keyof F]][]).forEach(([key, initialValue]) => { 114 | stateFields.fields[key] = initialStateOfField(initialValue); 115 | }); 116 | 117 | const getters: GetterTree, S> = { 118 | [GetterTypes.ALL_FIELDS_VALID] ({ fields }): boolean { 119 | return Object.keys(fields).every((name: string) => fields[name].disabled || fields[name].error === false); 120 | }, 121 | 122 | [GetterTypes.ANY_FIELD_CHANGED] ({ fields }): boolean { 123 | return Object.keys(fields).some((name: string) => fields[name].dirty === true && !fields[name].disabled); 124 | }, 125 | 126 | [GetterTypes.FIELD_VALUES] ({ fields }): Partial { 127 | const keyValue: Partial = {}; 128 | (Object.entries(fields) as [keyof F, FormField][]).forEach(([key, formField]) => { 129 | keyValue[key] = formField.value; 130 | }); 131 | return keyValue; 132 | }, 133 | 134 | [GetterTypes.FIELD_ERRORS] ({ fields }): Partial> { 135 | const keyValue: { [key in keyof F]?: ValidationResult } = {}; 136 | (Object.entries(fields) as [keyof F, FormField][]).forEach(([key, formField]) => { 137 | keyValue[key] = formField.error; 138 | if (formField.disabled) { 139 | keyValue[key] = false; 140 | } 141 | }); 142 | return keyValue; 143 | }, 144 | 145 | [GetterTypes.FIELD_EDITABILITIES] ({ fields }): Partial> { 146 | const keyValue: { [key in keyof F]?: boolean } = {}; 147 | (Object.entries(fields) as [keyof F, FormField][]).forEach(([key, formField]) => { 148 | keyValue[key] = !formField.disabled; 149 | }); 150 | return keyValue; 151 | }, 152 | 153 | [GetterTypes.FIELD_DIRTINESSES] ({ fields }): Partial> { 154 | const keyValue: { [key in keyof F]?: boolean } = {}; 155 | (Object.entries(fields) as [keyof F, FormField][]).forEach(([key, formField]) => { 156 | keyValue[key] = formField.dirty; 157 | }); 158 | return keyValue; 159 | } 160 | }; 161 | 162 | const mutations: MutationTree> = { 163 | [MutationTypes.SET_FIELD_VALUE] (state, payload) { 164 | state.fields[payload.name].value = payload.value; 165 | }, 166 | 167 | [MutationTypes.SET_FIELD_ERROR] (state, { name, error }: { name: keyof F; error: ValidationResult; }) { 168 | state.fields[name].error = error; 169 | }, 170 | 171 | [MutationTypes.SET_FIELD_EDITABILITY] (state, { name, editable }: { name: keyof F; editable: boolean; }) { 172 | state.fields[name].disabled = !editable; 173 | }, 174 | 175 | [MutationTypes.SET_FIELD_EDITABILITIES_BULK] (state, fields: { [key: string]: boolean; }) { 176 | Object.keys(fields).forEach((fieldKey) => { 177 | state.fields[fieldKey].disabled = !fields[fieldKey]; 178 | }); 179 | }, 180 | 181 | [MutationTypes.SET_FIELD_DIRTINESS] (state, { name, dirty }: { name: keyof F; dirty: boolean; }) { 182 | state.fields[name].dirty = dirty; 183 | }, 184 | 185 | [MutationTypes.INITIALIZE_FIELDS] (state, fields: { [key: string]: any; }) { 186 | Object.keys(state.fields).forEach((fieldKey) => { 187 | state.fields[fieldKey] = initialStateOfField(fields[fieldKey]); 188 | }); 189 | }, 190 | 191 | [MutationTypes.ENABLE_VALIDATION] (state, name: keyof F) { 192 | state.fields[name].validationEnabled = true; 193 | }, 194 | 195 | [MutationTypes.ENABLE_ALL_VALIDATIONS] (state) { 196 | (Object.keys(state.fields) as (keyof F)[]).forEach((fieldKey) => { 197 | state.fields[fieldKey].validationEnabled = true 198 | }); 199 | }, 200 | 201 | [MutationTypes.SET_FIELDS_PRISTINE] (state) { 202 | Object.keys(state.fields).forEach((fieldKey) => { 203 | state.fields[fieldKey].dirty = false; 204 | }); 205 | } 206 | }; 207 | 208 | const actions: ActionTree, S> = { 209 | async [ActionTypes.SET_FIELD_VALUE] ({ state, commit, dispatch }, { name, value }: { name: T; value: F[T]; }) { 210 | if (!state.fields[name].disabled) { 211 | commit(MutationTypes.SET_FIELD_DIRTINESS, { name, dirty: true }); 212 | commit(MutationTypes.SET_FIELD_VALUE, { name, value }); 213 | await dispatch(ActionTypes.VALIDATE_FIELDS); 214 | } 215 | }, 216 | 217 | async [ActionTypes.SET_FIELD_EDITABILITY] ({ commit, dispatch }, { name, editable }: { name: T; editable: boolean; }) { 218 | commit(MutationTypes.SET_FIELD_EDITABILITY, { name, editable }); 219 | await dispatch(ActionTypes.VALIDATE_FIELDS); 220 | }, 221 | 222 | async [ActionTypes.SET_FIELDS_BULK] ({ commit, dispatch }, fields: { [key in T]: F[T] }) { 223 | commit(MutationTypes.INITIALIZE_FIELDS, fields); 224 | await dispatch(ActionTypes.VALIDATE_FIELDS); 225 | }, 226 | 227 | async [ActionTypes.SET_FIELD_EDITABILITIES_BULK] ({ commit, dispatch }, fields: { [key in T]: boolean }) { 228 | commit(MutationTypes.SET_FIELD_EDITABILITIES_BULK, fields); 229 | await dispatch(ActionTypes.VALIDATE_FIELDS); 230 | }, 231 | 232 | [ActionTypes.RESET_FIELDS] ({ commit }): void { 233 | commit(MutationTypes.INITIALIZE_FIELDS, initialFields); 234 | }, 235 | 236 | async [ActionTypes.VALIDATE_FIELDS] ({ state, commit, getters }) { 237 | Object.keys(state.fields).forEach(async (name: string) => { 238 | const validatorsForField: Validator[] = validators[name]; 239 | if (validatorsForField) { 240 | let errorForField: false | string = false; 241 | validatorsForField.some((validatorForField) => { 242 | const validatorResult = validatorForField(getters[GetterTypes.FIELD_VALUES], getters); 243 | 244 | if (validatorResult instanceof Array) { 245 | if (validatorResult[1].instant === true || state.fields[name].validationEnabled) { 246 | errorForField = validatorResult[0](getters[GetterTypes.FIELD_VALUES], getters); 247 | } 248 | } else if (state.fields[name].validationEnabled) { 249 | errorForField = validatorResult; 250 | } 251 | return !!errorForField; 252 | }); 253 | 254 | if (state.fields[name].error !== errorForField) { 255 | commit(MutationTypes.SET_FIELD_ERROR, { name, error: errorForField }); 256 | } 257 | } 258 | }); 259 | }, 260 | 261 | async [ActionTypes.ENABLE_VALIDATION] ({ dispatch, commit }, key: T) { 262 | commit(MutationTypes.ENABLE_VALIDATION, key); 263 | return dispatch(ActionTypes.VALIDATE_FIELDS); 264 | }, 265 | 266 | async [ActionTypes.ENABLE_ALL_VALIDATIONS] ({ dispatch, commit }) { 267 | commit(MutationTypes.ENABLE_ALL_VALIDATIONS); 268 | return dispatch(ActionTypes.VALIDATE_FIELDS); 269 | }, 270 | 271 | async [ActionTypes.SET_FIELDS_PRISTINE] ({ commit }) { 272 | commit(MutationTypes.SET_FIELDS_PRISTINE); 273 | } 274 | }; 275 | 276 | return { 277 | validatableState: { 278 | state: { 279 | ...stateFields 280 | }, 281 | mutations, 282 | getters, 283 | actions 284 | } 285 | }; 286 | } 287 | 288 | export default buildModule; 289 | 290 | /** 291 | * Function to register validatable state module to the instance of Vuex.Store 292 | * @param store - The instance of Vuex.Store which is registered this module 293 | * @param parentNameSpace - Namespace (slash separated) which this module belongs: "", undefined means root 294 | * @param initialFields - Field names with initial variable 295 | * @param validators - Validators for each field 296 | * @example 297 | * register( 298 | * store, 299 | * "user/user-profile-form" 300 | * { name: null, age: null }, 301 | * { 302 | * name: [ 303 | * ({ name }) => name && name.length > 2 304 | * ], 305 | * age: [ 306 | * ({ age }) => age && age > 0 307 | * ] 308 | * } 309 | * ) 310 | */ 311 | export const register = (store: Store, parentNameSpace: string = "", initialFields: F, validators: ValidatorTree) => { 312 | const namespace: string[] = (parentNameSpace + "/validatableState").split("/").filter((name) => name !== ""); 313 | store.registerModule(namespace, buildModule(initialFields, validators)["validatableState"]); 314 | } 315 | -------------------------------------------------------------------------------- /test/index.test.ts: -------------------------------------------------------------------------------- 1 | import Vue from "vue"; 2 | import Vuex from "vuex"; 3 | import { register, ActionTypes, GetterTypes } from "../src/index"; 4 | 5 | Vue.use(Vuex); 6 | const moduleInternalKey = "validatableState"; 7 | 8 | describe("vuex-validatable-field-module", () => { 9 | const setupStore = (opt: { initialFields?: {}; validators?: {}; gettersOnCaller? : {}; } = {}) => { 10 | const initialFields = opt.initialFields || { 11 | name: null, 12 | age: null, 13 | subscribed: false 14 | }; 15 | 16 | const store = new Vuex.Store({ 17 | state: {}, 18 | getters: opt.gettersOnCaller || {}, 19 | actions: {}, 20 | mutations: {}, 21 | }); 22 | 23 | register(store, "", initialFields, opt.validators || {}); 24 | return store; 25 | }; 26 | 27 | describe("Initializing", () => { 28 | it("The store gets initial values and setup meta info on under the internal key", () => { 29 | const store = setupStore(); 30 | expect(store.state[moduleInternalKey]).toEqual({ 31 | fields: { 32 | name: { 33 | value: null, 34 | error: false, 35 | disabled: false, 36 | dirty: false, 37 | validationEnabled: false 38 | }, 39 | age: { 40 | value: null, 41 | error: false, 42 | disabled: false, 43 | dirty: false, 44 | validationEnabled: false 45 | }, 46 | subscribed: { 47 | value: false, 48 | error: false, 49 | disabled: false, 50 | dirty: false, 51 | validationEnabled: false 52 | } 53 | } 54 | }); 55 | }); 56 | }); 57 | 58 | describe("Mutations", () => { 59 | it("SET_FIELD_VALUE updates field's value", () => { 60 | const store = setupStore(); 61 | expect(store.state[moduleInternalKey].fields.age.value).toBe(null); 62 | store.commit("SET_FIELD_VALUE", { name: "age", value: 14 }); 63 | expect(store.state[moduleInternalKey].fields.age.value).toBe(14); 64 | }); 65 | 66 | it("SET_FIELD_ERROR updates field's error", () => { 67 | const store = setupStore(); 68 | expect(store.state[moduleInternalKey].fields.name.error).toBe(false); 69 | store.commit("SET_FIELD_ERROR", { name: "name", error: "the error message" }); 70 | expect(store.state[moduleInternalKey].fields.name.error).toBe("the error message"); 71 | }); 72 | 73 | it("SET_FIELD_EDITABILITY updates field's disableness", () => { 74 | const store = setupStore(); 75 | expect(store.state[moduleInternalKey].fields.subscribed.disabled).toBe(false); 76 | store.commit("SET_FIELD_EDITABILITY", { name: "subscribed", editable: false }); 77 | expect(store.state[moduleInternalKey].fields.subscribed.disabled).toBe(true); 78 | }); 79 | 80 | it("INITIALIZE_FIELDS updates multiple field's at once", () => { 81 | const store = setupStore(); 82 | store.commit("INITIALIZE_FIELDS", { name: "Izuku Midoriya", age: 15, subscribed: true }); 83 | expect(store.state[moduleInternalKey].fields.name.value).toBe("Izuku Midoriya"); 84 | expect(store.state[moduleInternalKey].fields.age.value).toBe(15); 85 | expect(store.state[moduleInternalKey].fields.subscribed.value).toBe(true); 86 | }); 87 | 88 | it("ENABLE_ALL_VALIDATIONS updates all validationEnabled flag as true", () => { 89 | const store = setupStore(); 90 | expect( 91 | Object.keys(store.state[moduleInternalKey].fields).map(key => store.state[moduleInternalKey].fields[key].validationEnabled) 92 | ).toEqual([false, false, false]) 93 | store.commit("ENABLE_ALL_VALIDATIONS"); 94 | expect( 95 | Object.keys(store.state[moduleInternalKey].fields).map(key => store.state[moduleInternalKey].fields[key].validationEnabled) 96 | ).toEqual([true, true, true]) 97 | }); 98 | 99 | it("ENABLE_VALIDATION updates validationEnabled flag on a specified field as true", () => { 100 | const store = setupStore(); 101 | expect( 102 | Object.keys(store.state[moduleInternalKey].fields).map(key => store.state[moduleInternalKey].fields[key].validationEnabled) 103 | ).toEqual([false, false, false]) 104 | store.commit("ENABLE_VALIDATION", "subscribed"); 105 | expect( 106 | Object.keys(store.state[moduleInternalKey].fields).map(key => store.state[moduleInternalKey].fields[key].validationEnabled) 107 | ).toEqual([false, false, true]) 108 | }); 109 | 110 | it("SET_FIELD_DIRTINESS updates drity flag", () => { 111 | const store = setupStore(); 112 | expect(store.state[moduleInternalKey].fields.name.dirty).toBe(false); 113 | store.commit("SET_FIELD_DIRTINESS", { name: "name", dirty: true }); 114 | expect(store.state[moduleInternalKey].fields.name.dirty).toBe(true); 115 | }); 116 | 117 | it("SET_FIELDS_PRISTINE updates all drity flags false", () => { 118 | const store = setupStore(); 119 | store.commit("SET_FIELD_DIRTINESS", { name: "name", dirty: true }); 120 | store.commit("SET_FIELD_DIRTINESS", { name: "age", dirty: true }); 121 | expect(store.state[moduleInternalKey].fields.name.dirty).toBe(true); 122 | expect(store.state[moduleInternalKey].fields.age.dirty).toBe(true); 123 | expect(store.state[moduleInternalKey].fields.subscribed.dirty).toBe(false); 124 | store.commit("SET_FIELDS_PRISTINE"); 125 | expect(store.state[moduleInternalKey].fields.name.dirty).toBe(false); 126 | expect(store.state[moduleInternalKey].fields.age.dirty).toBe(false); 127 | expect(store.state[moduleInternalKey].fields.subscribed.dirty).toBe(false); 128 | }); 129 | }); 130 | 131 | describe("Getters", () => { 132 | describe("ALL_FIELDS_VALID", () => { 133 | it("return true if all errors are false", () => { 134 | const store = setupStore(); 135 | expect(store.getters[GetterTypes.ALL_FIELDS_VALID]).toBe(true); 136 | }); 137 | 138 | it("return false if any field has error", () => { 139 | const store = setupStore(); 140 | store.commit("SET_FIELD_ERROR", { name: "name", error: "the error message" }); 141 | expect(store.getters[GetterTypes.ALL_FIELDS_VALID]).toBe(false); 142 | }); 143 | 144 | it("return true if the field has error is disabled", () => { 145 | const store = setupStore(); 146 | store.commit("SET_FIELD_ERROR", { name: "name", error: "the error message" }); 147 | store.commit("SET_FIELD_EDITABILITY", { name: "name", editable: false }); 148 | expect(store.getters[GetterTypes.ALL_FIELDS_VALID]).toBe(true); 149 | }); 150 | }); 151 | 152 | describe("ANY_FIELD_CHANGED", () => { 153 | it("returns false if any field is not changed", () => { 154 | const store = setupStore(); 155 | expect(store.getters[GetterTypes.ANY_FIELD_CHANGED]).toBe(false); 156 | }); 157 | 158 | it("returns true if any field is changed", () => { 159 | const store = setupStore(); 160 | store.dispatch(ActionTypes.SET_FIELD_VALUE, { name: "name", value: "new data" }); 161 | expect(store.getters[GetterTypes.ANY_FIELD_CHANGED]).toBe(true); 162 | }); 163 | 164 | it("returns false if the changed field is disabled", () => { 165 | const store = setupStore(); 166 | store.dispatch(ActionTypes.SET_FIELD_VALUE, { name: "name", value: "new data" }); 167 | store.commit("SET_FIELD_EDITABILITY", { name: "name", editable: false }); 168 | expect(store.getters[GetterTypes.ANY_FIELD_CHANGED]).toBe(false); 169 | }); 170 | }); 171 | 172 | describe("FIELD_VALUES", () => { 173 | it("returns key value pair of field's value", () => { 174 | const store = setupStore(); 175 | expect(store.getters[GetterTypes.FIELD_VALUES]).toEqual({ 176 | age: null, 177 | name: null, 178 | subscribed: false 179 | }); 180 | }); 181 | }); 182 | 183 | describe("FIELD_ERRORS", () => { 184 | it("returns key value pair of field's error", () => { 185 | const store = setupStore(); 186 | expect(store.getters[GetterTypes.FIELD_ERRORS]).toEqual({ 187 | age: false, 188 | name: false, 189 | subscribed: false 190 | }); 191 | 192 | store.commit("SET_FIELD_ERROR", { name: "name", error: "the error message" }); 193 | expect(store.getters[GetterTypes.FIELD_ERRORS]).toEqual({ 194 | age: false, 195 | name: "the error message", 196 | subscribed: false 197 | }); 198 | }); 199 | 200 | it("doesn't handle as error if the field which has error is disabled", () => { 201 | const store = setupStore(); 202 | store.commit("SET_FIELD_ERROR", { name: "name", error: "the error message" }); 203 | store.commit("SET_FIELD_EDITABILITY", { name: "name", editable: false }); 204 | expect(store.getters[GetterTypes.FIELD_ERRORS]).toEqual({ 205 | age: false, 206 | name: false, 207 | subscribed: false 208 | }); 209 | }); 210 | }); 211 | 212 | describe("FIELD_EDITABILITIES", () => { 213 | it("returns key value pair of field's editability", () => { 214 | const store = setupStore(); 215 | expect(store.getters[GetterTypes.FIELD_EDITABILITIES]).toEqual({ 216 | age: true, 217 | name: true, 218 | subscribed: true 219 | }); 220 | }); 221 | }); 222 | 223 | describe("FIELD_DIRTINESSES", () => { 224 | it("returns key value pair of field's dirtiness", () => { 225 | const store = setupStore(); 226 | expect(store.getters[GetterTypes.FIELD_DIRTINESSES]).toEqual({ 227 | age: false, 228 | name: false, 229 | subscribed: false 230 | }); 231 | }); 232 | }); 233 | }); 234 | 235 | describe("Actions", () => { 236 | const ageShouldBeAdult = () => [({ age }) => age && age > 21 ? false : "should be an adult", { instant: true }]; 237 | 238 | describe("SET_FIELD_VALUE", () => { 239 | it("sets new value for field", async () => { 240 | const store = setupStore(); 241 | await store.dispatch(ActionTypes.SET_FIELD_VALUE, { name: "subscribed", value: true }); 242 | expect(store.getters[GetterTypes.FIELD_VALUES]).toEqual({ 243 | name: null, 244 | age: null, 245 | subscribed: true 246 | }); 247 | }); 248 | 249 | it("then runs validation", async () => { 250 | const store = setupStore({ 251 | validators: { 252 | age: [ 253 | ageShouldBeAdult 254 | ] 255 | } 256 | }); 257 | await store.dispatch(ActionTypes.SET_FIELD_VALUE, { name: "subscribed", value: true }); 258 | expect(store.getters[GetterTypes.FIELD_ERRORS].age).toBe("should be an adult"); 259 | }); 260 | 261 | it("then make field dirty", async () => { 262 | const store = setupStore(); 263 | await store.dispatch(ActionTypes.SET_FIELD_VALUE, { name: "subscribed", value: true }); 264 | expect(store.getters[GetterTypes.FIELD_DIRTINESSES]).toEqual({ 265 | name: false, 266 | age: false, 267 | subscribed: true 268 | }); 269 | }); 270 | 271 | describe("the field is disabled", () => { 272 | it("doesn't set new value", async () => { 273 | const store = setupStore(); 274 | store.commit("SET_FIELD_EDITABILITY", { name: "subscribed", editable: false }); 275 | await store.dispatch(ActionTypes.SET_FIELD_VALUE, { name: "subscribed", value: true }); 276 | expect(store.getters[GetterTypes.FIELD_VALUES]).toEqual({ 277 | name: null, 278 | age: null, 279 | subscribed: false 280 | }); 281 | }); 282 | 283 | it("doesn't run validation", async () => { 284 | const store = setupStore({ 285 | validators: { 286 | age: [ 287 | ageShouldBeAdult 288 | ] 289 | } 290 | }); 291 | store.commit("SET_FIELD_EDITABILITY", { name: "subscribed", editable: false }); 292 | await store.dispatch(ActionTypes.SET_FIELD_VALUE, { name: "subscribed", value: true }); 293 | expect(store.getters[GetterTypes.FIELD_ERRORS].age).toBe(false); 294 | }); 295 | }); 296 | }); 297 | 298 | describe("SET_FIELD_EDITABILITY", () => { 299 | it("sets editability for field", async () => { 300 | const store = setupStore(); 301 | await store.dispatch(ActionTypes.SET_FIELD_EDITABILITY, { name: "subscribed", editable: false }); 302 | expect(store.getters[GetterTypes.FIELD_EDITABILITIES]).toEqual({ 303 | name: true, 304 | age: true, 305 | subscribed: false 306 | }); 307 | }); 308 | 309 | it("then runs validation", async () => { 310 | const store = setupStore({ 311 | validators: { 312 | age: [ 313 | ageShouldBeAdult 314 | ] 315 | } 316 | }); 317 | await store.dispatch(ActionTypes.SET_FIELD_EDITABILITY, { name: "subscribed", editable: false }); 318 | expect(store.getters[GetterTypes.FIELD_ERRORS].age).toBe("should be an adult"); 319 | }); 320 | }); 321 | 322 | describe("SET_FIELD_EDITABILITIES_BULK", () => { 323 | it("sets multiple fields' editabilities", async () => { 324 | const store = setupStore(); 325 | await store.dispatch(ActionTypes.SET_FIELD_EDITABILITIES_BULK, { name: false, age: true, subscribed: false }); 326 | expect(store.getters[GetterTypes.FIELD_EDITABILITIES]).toEqual({ 327 | name: false, 328 | age: true, 329 | subscribed: false 330 | }); 331 | }); 332 | 333 | it("then runs validation", async () => { 334 | const store = setupStore({ 335 | validators: { 336 | age: [ageShouldBeAdult] 337 | } 338 | }); 339 | await store.dispatch(ActionTypes.SET_FIELD_EDITABILITIES_BULK, { name: false, age: true, subscribed: false }); 340 | expect(store.getters[GetterTypes.FIELD_ERRORS].age).toBe("should be an adult"); 341 | }); 342 | }); 343 | 344 | describe("SET_FIELDS_BULK", () => { 345 | it("sets multiple fields", async () => { 346 | const store = setupStore(); 347 | await store.dispatch(ActionTypes.SET_FIELDS_BULK, { name: "Izuku Midoriya", age: 15, subscribed: true }); 348 | expect(store.getters[GetterTypes.FIELD_VALUES]).toEqual({ 349 | name: "Izuku Midoriya", 350 | age: 15, 351 | subscribed: true 352 | }); 353 | }); 354 | 355 | it("then runs validation", async () => { 356 | const store = setupStore({ 357 | validators: { 358 | age: [ 359 | ageShouldBeAdult 360 | ] 361 | } 362 | }); 363 | await store.dispatch(ActionTypes.SET_FIELDS_BULK, { name: "Izuku Midoriya", age: 15, subscribed: true }); 364 | expect(store.getters[GetterTypes.FIELD_ERRORS].age).toBe("should be an adult"); 365 | }); 366 | }); 367 | 368 | describe("RESET_FIELDS", () => { 369 | it("resets fields with initial data", () => { 370 | const store = setupStore(); 371 | store.commit("INITIALIZE_FIELDS", { name: "Izuku Midoriya", age: 15, subscribed: true }); 372 | expect(store.getters[GetterTypes.FIELD_VALUES]).toEqual({ 373 | name: "Izuku Midoriya", 374 | age: 15, 375 | subscribed: true 376 | }); 377 | store.dispatch(ActionTypes.RESET_FIELDS); 378 | expect(store.getters[GetterTypes.FIELD_VALUES]).toEqual({ 379 | name: null, 380 | age: null, 381 | subscribed: false 382 | }); 383 | }); 384 | }); 385 | 386 | describe("VALIDATE_FIELDS", () => { 387 | describe("validationEnabled is flagged", () => { 388 | it("store error message if validator returns", async () => { 389 | const mockAge = jest.fn().mockReturnValue("error message on age"); 390 | const store = setupStore({ 391 | validators: { 392 | age: [ 393 | () => mockAge() 394 | ] 395 | } 396 | }); 397 | 398 | store.commit("ENABLE_ALL_VALIDATIONS"); 399 | await store.dispatch(ActionTypes.VALIDATE_FIELDS); 400 | 401 | expect(store.getters[GetterTypes.FIELD_ERRORS].age).toBe("error message on age"); 402 | }); 403 | 404 | it("store false if validator doesn't return error message", async () => { 405 | const mockAge = jest.fn().mockReturnValue(false); 406 | const store = setupStore({ 407 | validators: { 408 | age: [ 409 | () => mockAge() 410 | ] 411 | } 412 | }); 413 | 414 | store.commit("ENABLE_ALL_VALIDATIONS"); 415 | await store.dispatch(ActionTypes.VALIDATE_FIELDS); 416 | 417 | expect(store.getters[GetterTypes.FIELD_ERRORS].age).toBe(false); 418 | }); 419 | 420 | describe("if given validator for multiple fields", () => { 421 | it("runs all validations", async () => { 422 | const mockAge = jest.fn(); 423 | const mockName = jest.fn(); 424 | const store = setupStore({ 425 | validators: { 426 | name: [ 427 | () => mockName() 428 | ], 429 | age: [ 430 | () => mockAge() 431 | ] 432 | } 433 | }); 434 | 435 | store.commit("ENABLE_ALL_VALIDATIONS"); 436 | await store.dispatch(ActionTypes.VALIDATE_FIELDS); 437 | 438 | expect(mockName).toHaveBeenCalled(); 439 | expect(mockAge).toHaveBeenCalled(); 440 | }); 441 | 442 | it("gives all fields for each validator", async () => { 443 | const mockName = jest.fn(); 444 | const store = setupStore({ 445 | validators: { 446 | name: [ 447 | param => mockName(param) 448 | ] 449 | } 450 | }); 451 | 452 | store.commit("ENABLE_ALL_VALIDATIONS"); 453 | await store.dispatch(ActionTypes.VALIDATE_FIELDS); 454 | 455 | expect(mockName).toHaveBeenCalledWith({ name: null, age: null, subscribed: false }); 456 | }); 457 | 458 | it("gives getters to validator", async () => { 459 | const mockName = jest.fn(); 460 | const store = setupStore({ 461 | validators: { 462 | name: [ 463 | (_param, getters) => mockName(getters.theGetterOnMainStore) 464 | ] 465 | }, 466 | gettersOnCaller: { 467 | theGetterOnMainStore: () => "Hello I'm on main store" 468 | } 469 | }); 470 | 471 | expect(store.getters.theGetterOnMainStore).toBe("Hello I'm on main store"); 472 | 473 | store.commit("ENABLE_ALL_VALIDATIONS"); 474 | await store.dispatch(ActionTypes.VALIDATE_FIELDS); 475 | 476 | expect(mockName).toHaveBeenCalledWith("Hello I'm on main store"); 477 | }); 478 | }); 479 | 480 | describe("if given multiple validators on a single fields", () => { 481 | it("run all validations until gets error", async () => { 482 | const mockNameFirstValidator = jest.fn().mockReturnValue(false); 483 | const mockNameSecondValidator = jest.fn().mockReturnValue("error message"); 484 | const mockNameThirdValidator = jest.fn(); 485 | const store = setupStore({ 486 | validators: { 487 | name: [ 488 | () => mockNameFirstValidator(), 489 | () => mockNameSecondValidator(), 490 | () => mockNameThirdValidator() 491 | ] 492 | } 493 | }); 494 | 495 | store.commit("ENABLE_ALL_VALIDATIONS"); 496 | await store.dispatch(ActionTypes.VALIDATE_FIELDS); 497 | 498 | expect(mockNameFirstValidator).toHaveBeenCalled(); 499 | expect(mockNameSecondValidator).toHaveBeenCalled(); 500 | expect(mockNameThirdValidator).not.toHaveBeenCalled(); 501 | }); 502 | }); 503 | }); 504 | 505 | describe("state.validate is not flagged", () => { 506 | describe("but a validator enables instant option", () => { 507 | it("run only enabled validation", async () => { 508 | const mockNameFirstValidator = jest.fn().mockReturnValue([() => "error message 1", { instant: false }]); 509 | const mockNameSecondValidator = jest.fn().mockReturnValue("error message 2"); 510 | const mockNameThirdValidator = jest.fn().mockReturnValue([() => "error message 3", { instant: true }]); 511 | const store = setupStore({ 512 | validators: { 513 | name: [ 514 | () => mockNameFirstValidator(), 515 | () => mockNameSecondValidator(), 516 | () => mockNameThirdValidator() 517 | ] 518 | } 519 | }); 520 | 521 | await store.dispatch(ActionTypes.VALIDATE_FIELDS); 522 | 523 | expect(store.getters[GetterTypes.FIELD_ERRORS].name).toBe("error message 3"); 524 | }); 525 | }); 526 | }); 527 | }); 528 | 529 | describe("ENABLE_ALL_VALIDATIONS", () => { 530 | it("enable all validationEnabled flag", () => { 531 | const store = setupStore(); 532 | expect( 533 | Object.keys(store.state[moduleInternalKey].fields).map(key => store.state[moduleInternalKey].fields[key].validationEnabled) 534 | ).toEqual([false, false, false]) 535 | store.dispatch(ActionTypes.ENABLE_ALL_VALIDATIONS); 536 | expect( 537 | Object.keys(store.state[moduleInternalKey].fields).map(key => store.state[moduleInternalKey].fields[key].validationEnabled) 538 | ).toEqual([true, true, true]) 539 | }); 540 | }); 541 | 542 | describe("ENABLE_VALIDATION", () => { 543 | it("enable validationEnabled flag on a specified field", () => { 544 | const store = setupStore(); 545 | expect( 546 | Object.keys(store.state[moduleInternalKey].fields).map(key => store.state[moduleInternalKey].fields[key].validationEnabled) 547 | ).toEqual([false, false, false]) 548 | store.dispatch(ActionTypes.ENABLE_VALIDATION, "age"); 549 | expect( 550 | Object.keys(store.state[moduleInternalKey].fields).map(key => store.state[moduleInternalKey].fields[key].validationEnabled) 551 | ).toEqual([false, true, false]) 552 | }); 553 | }); 554 | 555 | describe("SET_FIELDS_PRISTINE", () => { 556 | it("makes all fields non-dirty", () => { 557 | const store = setupStore(); 558 | store.commit("SET_FIELD_DIRTINESS", { name: "name", dirty: true }); 559 | store.commit("SET_FIELD_DIRTINESS", { name: "age", dirty: true }); 560 | expect(store.state[moduleInternalKey].fields.name.dirty).toBe(true); 561 | expect(store.state[moduleInternalKey].fields.age.dirty).toBe(true); 562 | expect(store.state[moduleInternalKey].fields.subscribed.dirty).toBe(false); 563 | store.dispatch(ActionTypes.SET_FIELDS_PRISTINE); 564 | expect(store.state[moduleInternalKey].fields.name.dirty).toBe(false); 565 | expect(store.state[moduleInternalKey].fields.age.dirty).toBe(false); 566 | expect(store.state[moduleInternalKey].fields.subscribed.dirty).toBe(false); 567 | }); 568 | }); 569 | }); 570 | }); 571 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "lib": [ 5 | "es6", 6 | "es2017.object" 7 | ], 8 | "module": "es6", 9 | "strict": true, 10 | "importHelpers": true, 11 | "moduleResolution": "node", 12 | "experimentalDecorators": true, 13 | "esModuleInterop": true, 14 | "allowSyntheticDefaultImports": true, 15 | "noImplicitAny": false, 16 | "noImplicitThis": false, 17 | "sourceMap": true, 18 | "baseUrl": ".", 19 | "declaration": true, 20 | "declarationDir": "dist", 21 | "outDir": "dist", 22 | "types": [ 23 | "jest" 24 | ], 25 | "paths": { 26 | "@/*": ["src/*"] 27 | } 28 | }, 29 | "include": [ 30 | "src" 31 | ] 32 | } 33 | --------------------------------------------------------------------------------