or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-vuelidate--core

Simple, lightweight model-based validation library for Vue.js applications with reactive validation rules and comprehensive error handling.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@vuelidate/core@2.0.x

To install, run

npx @tessl/cli install tessl/npm-vuelidate--core@2.0.0

0

# Vuelidate Core

1

2

Vuelidate 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.

3

4

## Package Information

5

6

- **Package Name**: @vuelidate/core

7

- **Package Type**: npm

8

- **Language**: JavaScript with TypeScript definitions

9

- **Installation**: `npm install @vuelidate/core`

10

- **Dependencies**: vue-demi (Vue 2/3 compatibility)

11

12

## Core Imports

13

14

```typescript

15

import { useVuelidate } from "@vuelidate/core";

16

```

17

18

For CommonJS:

19

20

```javascript

21

const { useVuelidate } = require("@vuelidate/core");

22

```

23

24

Additional exports:

25

26

```typescript

27

import { useVuelidate, CollectFlag } from "@vuelidate/core";

28

```

29

30

## Basic Usage

31

32

### Composition API

33

34

```typescript

35

import { reactive } from "vue";

36

import { useVuelidate } from "@vuelidate/core";

37

import { required, email } from "@vuelidate/validators";

38

39

export default {

40

setup() {

41

const state = reactive({

42

name: "",

43

email: ""

44

});

45

46

const rules = {

47

name: { required },

48

email: { required, email }

49

};

50

51

const v$ = useVuelidate(rules, state);

52

53

return { state, v$ };

54

}

55

};

56

```

57

58

### Options API

59

60

```javascript

61

import { useVuelidate } from "@vuelidate/core";

62

import { required, email } from "@vuelidate/validators";

63

64

export default {

65

data() {

66

return {

67

form: {

68

name: "",

69

email: ""

70

}

71

};

72

},

73

setup: () => ({ v$: useVuelidate() }),

74

validations() {

75

return {

76

form: {

77

name: { required },

78

email: { required, email }

79

}

80

};

81

}

82

};

83

```

84

85

## Architecture

86

87

Vuelidate Core is built around several key components:

88

89

- **Validation Engine**: Core validation processing with support for sync and async validators

90

- **Reactive State Management**: Integrates with Vue's reactivity system for real-time validation

91

- **Nested Validation**: Support for validating complex nested object structures

92

- **Child Component Integration**: Collect and aggregate validation state from child components

93

- **Caching System**: Intelligent result caching for performance optimization

94

- **Configuration System**: Global and local configuration options for validation behavior

95

96

## Capabilities

97

98

### Core Validation Function

99

100

Main composition function for creating validation instances with full TypeScript support and reactive state management.

101

102

```typescript { .api }

103

function useVuelidate(): Ref<Validation>;

104

function useVuelidate<

105

T extends {[key in keyof Vargs]: any},

106

Vargs extends ValidationArgs = ValidationArgs,

107

EState extends ExtractState<Vargs> = ExtractState<Vargs>

108

>(

109

validationsArgs: Ref<Vargs> | Vargs,

110

state: T | Ref<T> | ToRefs<T>,

111

globalConfig?: GlobalConfig

112

): Ref<Validation<Vargs, T>>;

113

```

114

115

### Child Component Collection

116

117

Control flags for collecting validation results from child components in parent-child component hierarchies.

118

119

```typescript { .api }

120

enum CollectFlag {

121

COLLECT_ALL = true,

122

COLLECT_NONE = false

123

}

124

```

125

126

### Validation Configuration

127

128

```typescript { .api }

129

interface GlobalConfig {

130

$registerAs?: string;

131

$scope?: string | number | symbol | boolean;

132

$stopPropagation?: boolean;

133

$autoDirty?: boolean;

134

$lazy?: boolean;

135

$externalResults?: ServerErrors | Ref<ServerErrors> | UnwrapRef<ServerErrors>;

136

$rewardEarly?: boolean;

137

currentVueInstance?: ComponentInternalInstance | null;

138

}

139

```

140

141

### Validation Rules System

142

143

```typescript { .api }

144

type ValidatorFn<T = any, K = any, S = any> = (

145

value: T,

146

siblingState: K,

147

vm: S

148

) => boolean | ValidatorResponse | Promise<boolean | ValidatorResponse>;

149

150

interface ValidatorResponse {

151

$valid: boolean;

152

[key: string]: any;

153

}

154

155

interface ValidationRuleWithoutParams<T = any> {

156

$validator: ValidatorFn<T>;

157

$message?: string | Ref<string> | (() => string);

158

}

159

160

interface ValidationRuleWithParams<P extends object = object, T = any> {

161

$validator: ValidatorFn<T>;

162

$message: (input: { $params: P }) => string;

163

$params: P;

164

}

165

166

type ValidationRule<T = any> =

167

| ValidationRuleWithParams<any, T>

168

| ValidationRuleWithoutParams<T>

169

| ValidatorFn<T>;

170

171

type ValidationRuleCollection<T = any> = Record<string, ValidationRule<T>>;

172

173

type ValidationArgs<T = unknown> = {

174

[key in keyof T]: ValidationArgs<T[key]> | ValidationRuleCollection<T[key]> | ValidationRule<T[key]>

175

};

176

```

177

178

### Validation State Interface

179

180

```typescript { .api }

181

interface BaseValidation<

182

T = unknown,

183

Vrules extends ValidationRuleCollection<T> | undefined = undefined,

184

> {

185

$model: T;

186

readonly $dirty: boolean;

187

readonly $error: boolean;

188

readonly $errors: ErrorObject[];

189

readonly $silentErrors: ErrorObject[];

190

readonly $externalResults: ErrorObject[];

191

readonly $invalid: boolean;

192

readonly $anyDirty: boolean;

193

readonly $pending: boolean;

194

readonly $path: string;

195

readonly $touch: () => void;

196

readonly $reset: () => void;

197

readonly $commit: () => void;

198

readonly $validate: () => Promise<boolean>;

199

readonly [key: string]: any;

200

}

201

202

type Validation<Vargs extends ValidationArgs = ValidationArgs, T = unknown> =

203

NestedValidations<Vargs, T> &

204

BaseValidation<T, Vargs extends ValidationRuleCollection ? Vargs : any> &

205

ChildValidations;

206

207

interface ChildValidations {

208

readonly $getResultsForChild: (key: string) => (BaseValidation & ChildValidations) | undefined;

209

readonly $clearExternalResults: () => void;

210

}

211

```

212

213

### Error Handling

214

215

```typescript { .api }

216

interface ErrorObject {

217

readonly $propertyPath: string;

218

readonly $property: string;

219

readonly $validator: string;

220

readonly $message: string | Ref<string>;

221

readonly $params: object;

222

readonly $pending: boolean;

223

readonly $response: any;

224

readonly $uid: string;

225

}

226

227

interface ServerErrors {

228

[key: string]: string | string[] | ServerErrors;

229

}

230

```

231

232

### Rule Result Types

233

234

```typescript { .api }

235

interface RuleResultWithoutParams {

236

readonly $message: string;

237

readonly $pending: boolean;

238

readonly $invalid: boolean;

239

readonly $response: any;

240

}

241

242

interface RuleResultWithParams<P extends object = object> extends RuleResultWithoutParams {

243

readonly $params: P;

244

}

245

246

type RuleResult = RuleResultWithoutParams | RuleResultWithParams;

247

```

248

249

### Type Utilities

250

251

```typescript { .api }

252

type ExtractState<Vargs extends ValidationArgs> =

253

Vargs extends ValidationRuleCollection

254

? ExtractStateLeaf<Vargs> & ChildStateLeafs<Vargs>

255

: ChildStateLeafs<Vargs>;

256

257

type ExtractStateLeaf<Vrules extends ValidationRuleCollection> =

258

Vrules extends ValidationRuleCollection<infer T> ? T : unknown;

259

260

type ChildStateLeafs<Vargs extends ValidationArgs = ValidationArgs> = {

261

[K in keyof Vargs]?: (

262

Vargs[K] extends ValidationRuleCollection

263

? ExtractStateLeaf<Vargs[K]>

264

: unknown

265

) & (

266

Vargs[K] extends Record<string, ValidationArgs>

267

? ChildStateLeafs<Vargs[K]>

268

: unknown

269

)

270

};

271

272

type NestedValidations<Vargs extends ValidationArgs = ValidationArgs, T = unknown> = {

273

readonly [K in keyof Vargs]: BaseValidation<

274

T extends Record<K, unknown> ? T[K] : unknown,

275

Vargs[K] extends ValidationRuleCollection ? Vargs[K] : undefined

276

> & (

277

Vargs[K] extends Record<string, ValidationArgs>

278

? NestedValidations<Vargs[K], T extends Record<K, unknown> ? T[K] : unknown>

279

: unknown

280

)

281

};

282

283

type ToRefs<T> = { [K in keyof T]: Ref<T[K]> };

284

```

285

286

## Advanced Usage Patterns

287

288

### Lazy Validation

289

290

```typescript

291

const v$ = useVuelidate(rules, state, { $lazy: true });

292

```

293

294

### Auto-Dirty Mode

295

296

```typescript

297

const v$ = useVuelidate(rules, state, { $autoDirty: true });

298

```

299

300

### External Server Errors

301

302

```typescript

303

const serverErrors = ref({});

304

const v$ = useVuelidate(rules, state, {

305

$externalResults: serverErrors

306

});

307

```

308

309

### Child Component Collection

310

311

```typescript

312

// Parent component

313

const v$ = useVuelidate({ $scope: 'parentForm' });

314

315

// Child component

316

const childV$ = useVuelidate(childRules, childState, {

317

$scope: 'parentForm',

318

$registerAs: 'childComponent'

319

});

320

```

321

322

### Reward Early Mode

323

324

```typescript

325

const v$ = useVuelidate(rules, state, { $rewardEarly: true });

326

```

327

328

## Validation Lifecycle

329

330

1. **Initialization**: Validation rules are processed and watchers are set up

331

2. **Reactive Updates**: State changes trigger validation re-evaluation

332

3. **Dirty State**: Validation errors become active after `$touch()` or model changes

333

4. **Async Handling**: Async validators set `$pending` state during execution

334

5. **Error Collection**: Results are aggregated and made available via `$errors`

335

6. **Cleanup**: Watchers are disposed when components unmount

336

337

## Common Patterns

338

339

### Form Validation

340

341

```typescript

342

// Check if form is ready to submit

343

if (!v$.$invalid && !v$.$pending) {

344

submitForm();

345

}

346

347

// Display errors

348

v$.$errors.forEach(error => {

349

console.log(`${error.$property}: ${error.$message}`);

350

});

351

```

352

353

### Manual Validation

354

355

```typescript

356

// Trigger validation manually

357

const isValid = await v$.$validate();

358

359

// Reset validation state

360

v$.$reset();

361

```

362

363

### Nested Object Validation

364

365

```typescript

366

const rules = {

367

user: {

368

name: { required },

369

address: {

370

street: { required },

371

city: { required }

372

}

373

}

374

};

375

376

// Access nested validation results

377

console.log(v$.user.name.$error);

378

console.log(v$.user.address.street.$errors);

379

```