Skip to content
This repository has been archived by the owner on Nov 15, 2017. It is now read-only.

Commit

Permalink
Add computed validation properties
Browse files Browse the repository at this point in the history
  • Loading branch information
fastner committed May 12, 2016
1 parent 673f127 commit 67d7020
Showing 1 changed file with 53 additions and 1 deletion.
54 changes: 53 additions & 1 deletion src/VuexValidator.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { reduce } from "lodash"
import { reduce, camelCase } from "lodash"

const validators = []
const validatorsMap = {}
Expand Down Expand Up @@ -30,6 +30,24 @@ class GlobalValidator {

const validator = new GlobalValidator()

function computedValidation(id, rulesLength)
{
return () =>
{
let allResults = true
for (let index = 0; index < rulesLength; index++)
{
const curResult = this[`${id}${index}`]

if (curResult !== true)
if (allResults === true)
allResults = curResult
else
allResults = allResults.concat(curResult)
}
}
}

function install(Vue, { validators: _validators } = { validators: [] })
{
/* eslint no-invalid-this: 0, no-console:0 */
Expand All @@ -54,6 +72,29 @@ function install(Vue, { validators: _validators } = { validators: [] })
this.$store.$validator = validator
validators.forEach((item) => item.injectStore(this.$store))
}

const options = this.$options
options.vuex = options.vuex || {}
const getters = options.vuex.getters = options.vuex.getters || {}

validators.forEach((item) =>
{
item.getProperties.forEach((prop) =>
{
const id = `\$valid\$${camelCase(prop)}`
const rules = item.getRulesByProperty(prop)
const rulesLength = rules.length
if (rulesLength > 0)
{
// TODO: Cache generated getters like Vuex do
rules.forEach((rule, index) =>
{
getters[`${id}${index}`] = (state) => rule.validatorFunction(state)
})
getters[id] = computedValidation(id, rulesLength)
}
})
})
}

const _init = Vue.prototype._init
Expand All @@ -62,6 +103,17 @@ function install(Vue, { validators: _validators } = { validators: [] })
options.init = options.init ? options.init.concat([ validatorInit ]) : validatorInit
_init.call(this, options)
}

// option merging (found in vuex)
const merge = Vue.config.optionMergeStrategies.computed
Vue.config.optionMergeStrategies.vuexValidator = (toVal, fromVal) =>
{
if (!toVal) return fromVal
if (!fromVal) return toVal
return {
getters: merge(toVal.getters, fromVal.getters)
}
}
}

export default {
Expand Down

0 comments on commit 67d7020

Please sign in to comment.