1
0
mirror of synced 2024-11-22 21:36:04 +03:00
vue-formulario/src/Formulario.ts

82 lines
2.5 KiB
TypeScript
Raw Normal View History

import { VueConstructor } from 'vue'
import rules from '@/validation/rules'
import messages from '@/validation/messages'
import merge from '@/utils/merge'
2020-10-09 22:58:28 +03:00
import FormularioForm from '@/FormularioForm.vue'
import FormularioGrouping from '@/FormularioGrouping.vue'
import FormularioInput from '@/FormularioInput.vue'
import {
ValidationContext,
CheckRuleFn,
CreateMessageFn,
} from '@/validation/validator'
interface FormularioOptions {
rules?: any;
messages?: Record<string, Function>;
}
2020-05-22 14:22:56 +03:00
2020-10-09 22:58:28 +03:00
// noinspection JSUnusedGlobalSymbols
2020-05-22 14:22:56 +03:00
/**
* The base formulario library.
*/
export default class Formulario {
public rules: Record<string, CheckRuleFn> = {}
public messages: Record<string, Function> = {}
2020-05-22 14:22:56 +03:00
constructor () {
this.rules = rules
this.messages = messages
2020-05-22 14:22:56 +03:00
}
/**
* Install vue formulario, and register its components.
*/
install (Vue: VueConstructor, options?: FormularioOptions): void {
2020-05-22 14:22:56 +03:00
Vue.prototype.$formulario = this
Vue.component('FormularioForm', FormularioForm)
Vue.component('FormularioGrouping', FormularioGrouping)
Vue.component('FormularioInput', FormularioInput)
2020-05-22 14:22:56 +03:00
this.extend(options || {})
}
/**
* Given a set of options, apply them to the pre-existing options.
*/
extend (extendWith: FormularioOptions): Formulario {
2020-05-22 14:22:56 +03:00
if (typeof extendWith === 'object') {
this.rules = merge(this.rules, extendWith.rules || {})
this.messages = merge(this.messages, extendWith.messages || {})
2020-05-22 14:22:56 +03:00
return this
}
throw new Error(`[Formulario]: Formulario.extend() should be passed an object (was ${typeof extendWith})`)
2020-05-22 14:22:56 +03:00
}
/**
* Get validation rules by merging any passed in with global rules.
*/
getRules (extendWith: Record<string, CheckRuleFn> = {}): Record<string, CheckRuleFn> {
return merge(this.rules, extendWith)
2020-05-22 14:22:56 +03:00
}
/**
* Get validation messages by merging any passed in with global messages.
*/
getMessages (vm: Vue, extendWith: Record<string, Function>): Record<string, CreateMessageFn> {
const raw = merge(this.messages || {}, extendWith)
const messages: Record<string, CreateMessageFn> = {}
for (const name in raw) {
messages[name] = (context: ValidationContext, ...args: any[]): string => {
return typeof raw[name] === 'string' ? raw[name] : raw[name](vm, context, ...args)
}
}
return messages
2020-05-22 14:22:56 +03:00
}
}