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

66 lines
2.1 KiB
TypeScript
Raw Normal View History

import merge from '@/utils/merge'
import validationRules from '@/validation/rules'
import validationMessages from '@/validation/messages'
2020-10-09 22:58:28 +03:00
import {
ValidationContext,
CheckRuleFn,
CreateMessageFn,
} from '@/validation/validator'
export interface FormularioOptions {
validationRules?: any;
validationMessages?: 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 validationRules: Record<string, CheckRuleFn> = {}
public validationMessages: Record<string, Function> = {}
constructor (options?: FormularioOptions) {
this.validationRules = validationRules
this.validationMessages = validationMessages
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.validationRules = merge(this.validationRules, extendWith.validationRules || {})
this.validationMessages = merge(this.validationMessages, extendWith.validationMessages || {})
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.validationRules, 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.validationMessages || {}, 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
}
}