vv-jsdt
Version:
validate based on vue2
70 lines (58 loc) • 2.04 kB
JavaScript
/**
* Created by chunyang.gao on 17/4/11.
*/
import RULES from './rules.js';
import warn from './warn';
import { is, objectAssign } from './util';
import { check } from './check-action';
class validator {
constructor(_vm) {
this.vm = _vm;
}
clear() {
this.$errors = {};
return this;
}
check(fields) {
const vm = this.vm;
const rules = vm.$options.vvlist;
fields = fields || Object.keys(rules);
return fields.map(field => check.call(vm, rules[field], field, vm._data[field], is('Array', rules[field]))).indexOf(false) === -1;
}
}
function init() {
const rules = this.$options.vvlist;
if (!rules) return;
this.VV = new validator(this);
this.__proto__.constructor.util.defineReactive(this.VV.__proto__, '$errors', {});
this.__proto__.constructor.util.defineReactive(this.VV.__proto__, 'invalid', true);
this.__proto__.constructor.util.defineReactive(this.VV.__proto__, 'valid', false);
Object.keys(rules).forEach(field => this.$watch(field, value => {
check.call(this, rules[field], field, value, is('Array', rules[field]));
}));
}
let installed = false;
export default function (_Vue, opts = {}) {
if (installed) {
warn('already installed.');
return;
}
validator.prototype.$rules = objectAssign({}, RULES, opts);
_Vue.mixin({
created: init
});
_Vue.component('vv-input', {
template: `<span v-bind:class="{'vuerify-invalid' : $parent.VV.$errors[field]}">
<input :value="value" ="$emit('input', $event.target.value)">
<span class="error" v-text="$parent.VV.$errors[field]"></span>
</span>`,
props: ['value', 'field']
});
_Vue.component('vv-textarea', {
template: `<span v-bind:class="{'vuerify-invalid' : $parent.VV.$errors[field]}">
<textarea :value="value" ="$emit('input', $event.target.value)"></textarea>
</span>`,
props: ['value', 'field']
});
installed = true;
}