Simple, lightweight model-based validation library for Vue.js applications with reactive validation rules and comprehensive error handling.
npx @tessl/cli install tessl/npm-vuelidate--core@2.0.0Vuelidate Core is a simple, lightweight model-based validation library for Vue.js applications. It provides reactive validation rules that integrate seamlessly with Vue's composition API and options API, supporting both Vue 2.x and Vue 3.0.
npm install @vuelidate/coreimport { useVuelidate } from "@vuelidate/core";For CommonJS:
const { useVuelidate } = require("@vuelidate/core");Additional exports:
import { useVuelidate, CollectFlag } from "@vuelidate/core";import { reactive } from "vue";
import { useVuelidate } from "@vuelidate/core";
import { required, email } from "@vuelidate/validators";
export default {
setup() {
const state = reactive({
name: "",
email: ""
});
const rules = {
name: { required },
email: { required, email }
};
const v$ = useVuelidate(rules, state);
return { state, v$ };
}
};import { useVuelidate } from "@vuelidate/core";
import { required, email } from "@vuelidate/validators";
export default {
data() {
return {
form: {
name: "",
email: ""
}
};
},
setup: () => ({ v$: useVuelidate() }),
validations() {
return {
form: {
name: { required },
email: { required, email }
}
};
}
};Vuelidate Core is built around several key components:
Main composition function for creating validation instances with full TypeScript support and reactive state management.
function useVuelidate(): Ref<Validation>;
function useVuelidate<
T extends {[key in keyof Vargs]: any},
Vargs extends ValidationArgs = ValidationArgs,
EState extends ExtractState<Vargs> = ExtractState<Vargs>
>(
validationsArgs: Ref<Vargs> | Vargs,
state: T | Ref<T> | ToRefs<T>,
globalConfig?: GlobalConfig
): Ref<Validation<Vargs, T>>;Control flags for collecting validation results from child components in parent-child component hierarchies.
enum CollectFlag {
COLLECT_ALL = true,
COLLECT_NONE = false
}interface GlobalConfig {
$registerAs?: string;
$scope?: string | number | symbol | boolean;
$stopPropagation?: boolean;
$autoDirty?: boolean;
$lazy?: boolean;
$externalResults?: ServerErrors | Ref<ServerErrors> | UnwrapRef<ServerErrors>;
$rewardEarly?: boolean;
currentVueInstance?: ComponentInternalInstance | null;
}type ValidatorFn<T = any, K = any, S = any> = (
value: T,
siblingState: K,
vm: S
) => boolean | ValidatorResponse | Promise<boolean | ValidatorResponse>;
interface ValidatorResponse {
$valid: boolean;
[key: string]: any;
}
interface ValidationRuleWithoutParams<T = any> {
$validator: ValidatorFn<T>;
$message?: string | Ref<string> | (() => string);
}
interface ValidationRuleWithParams<P extends object = object, T = any> {
$validator: ValidatorFn<T>;
$message: (input: { $params: P }) => string;
$params: P;
}
type ValidationRule<T = any> =
| ValidationRuleWithParams<any, T>
| ValidationRuleWithoutParams<T>
| ValidatorFn<T>;
type ValidationRuleCollection<T = any> = Record<string, ValidationRule<T>>;
type ValidationArgs<T = unknown> = {
[key in keyof T]: ValidationArgs<T[key]> | ValidationRuleCollection<T[key]> | ValidationRule<T[key]>
};interface BaseValidation<
T = unknown,
Vrules extends ValidationRuleCollection<T> | undefined = undefined,
> {
$model: T;
readonly $dirty: boolean;
readonly $error: boolean;
readonly $errors: ErrorObject[];
readonly $silentErrors: ErrorObject[];
readonly $externalResults: ErrorObject[];
readonly $invalid: boolean;
readonly $anyDirty: boolean;
readonly $pending: boolean;
readonly $path: string;
readonly $touch: () => void;
readonly $reset: () => void;
readonly $commit: () => void;
readonly $validate: () => Promise<boolean>;
readonly [key: string]: any;
}
type Validation<Vargs extends ValidationArgs = ValidationArgs, T = unknown> =
NestedValidations<Vargs, T> &
BaseValidation<T, Vargs extends ValidationRuleCollection ? Vargs : any> &
ChildValidations;
interface ChildValidations {
readonly $getResultsForChild: (key: string) => (BaseValidation & ChildValidations) | undefined;
readonly $clearExternalResults: () => void;
}interface ErrorObject {
readonly $propertyPath: string;
readonly $property: string;
readonly $validator: string;
readonly $message: string | Ref<string>;
readonly $params: object;
readonly $pending: boolean;
readonly $response: any;
readonly $uid: string;
}
interface ServerErrors {
[key: string]: string | string[] | ServerErrors;
}interface RuleResultWithoutParams {
readonly $message: string;
readonly $pending: boolean;
readonly $invalid: boolean;
readonly $response: any;
}
interface RuleResultWithParams<P extends object = object> extends RuleResultWithoutParams {
readonly $params: P;
}
type RuleResult = RuleResultWithoutParams | RuleResultWithParams;type ExtractState<Vargs extends ValidationArgs> =
Vargs extends ValidationRuleCollection
? ExtractStateLeaf<Vargs> & ChildStateLeafs<Vargs>
: ChildStateLeafs<Vargs>;
type ExtractStateLeaf<Vrules extends ValidationRuleCollection> =
Vrules extends ValidationRuleCollection<infer T> ? T : unknown;
type ChildStateLeafs<Vargs extends ValidationArgs = ValidationArgs> = {
[K in keyof Vargs]?: (
Vargs[K] extends ValidationRuleCollection
? ExtractStateLeaf<Vargs[K]>
: unknown
) & (
Vargs[K] extends Record<string, ValidationArgs>
? ChildStateLeafs<Vargs[K]>
: unknown
)
};
type NestedValidations<Vargs extends ValidationArgs = ValidationArgs, T = unknown> = {
readonly [K in keyof Vargs]: BaseValidation<
T extends Record<K, unknown> ? T[K] : unknown,
Vargs[K] extends ValidationRuleCollection ? Vargs[K] : undefined
> & (
Vargs[K] extends Record<string, ValidationArgs>
? NestedValidations<Vargs[K], T extends Record<K, unknown> ? T[K] : unknown>
: unknown
)
};
type ToRefs<T> = { [K in keyof T]: Ref<T[K]> };const v$ = useVuelidate(rules, state, { $lazy: true });const v$ = useVuelidate(rules, state, { $autoDirty: true });const serverErrors = ref({});
const v$ = useVuelidate(rules, state, {
$externalResults: serverErrors
});// Parent component
const v$ = useVuelidate({ $scope: 'parentForm' });
// Child component
const childV$ = useVuelidate(childRules, childState, {
$scope: 'parentForm',
$registerAs: 'childComponent'
});const v$ = useVuelidate(rules, state, { $rewardEarly: true });$touch() or model changes$pending state during execution$errors// Check if form is ready to submit
if (!v$.$invalid && !v$.$pending) {
submitForm();
}
// Display errors
v$.$errors.forEach(error => {
console.log(`${error.$property}: ${error.$message}`);
});// Trigger validation manually
const isValid = await v$.$validate();
// Reset validation state
v$.$reset();const rules = {
user: {
name: { required },
address: {
street: { required },
city: { required }
}
}
};
// Access nested validation results
console.log(v$.user.name.$error);
console.log(v$.user.address.street.$errors);