New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

vue3-form-validation

Package Overview
Dependencies
Maintainers
1
Versions
59
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vue3-form-validation - npm Package Compare versions

Comparing version 2.0.1 to 2.0.2

21

dist/composable/useValidation.d.ts
import { Ref } from 'vue';
import Form from '../Form';
export declare type SimpleRule<T = any> = (value: T) => Promise<string | unknown> | string | unknown;
export declare type SimpleRule<T = any> = (value: T) => Promise<unknown> | unknown;
export declare type KeyedRule<T = any> = {

@@ -18,17 +18,12 @@ key: string;

validating: boolean;
onBlur(): void;
};
declare type ValidateFormData<T> = T extends unknown ? {
[K in keyof T]: T[K] extends {
value: Ref<infer TValue> | infer TValue;
} ? Field<TValue> : T[K] extends Array<infer TArray> ? ValidateFormData<TArray>[] : never;
[K in keyof T]: T[K] extends Field<infer TValue> ? Field<TValue> : T[K] extends Array<infer TArray> ? ValidateFormData<TArray>[] : never;
} : never;
declare type UseValidation<T> = T extends unknown ? {
[K in keyof T]: T[K] extends {
value: Ref<infer TValue> | infer TValue;
} ? TransformedField<TValue> : T[K] extends Array<infer TArray> ? UseValidation<TArray>[] : never;
declare type TransformedFormData<T> = T extends unknown ? {
[K in keyof T]: T[K] extends Field<infer TValue> ? TransformedField<TValue> : T[K] extends Array<infer TArray> ? TransformedFormData<TArray>[] : never;
} : never;
declare type FormData<T> = T extends unknown ? {
[K in keyof T]: T[K] extends {
value: Ref<infer TValue> | infer TValue;
} ? TValue : T[K] extends Array<infer TArray> ? FormData<TArray>[] : never;
[K in keyof T]: T[K] extends Field<infer TValue> ? TValue : T[K] extends Array<infer TArray> ? FormData<TArray>[] : never;
} : never;

@@ -50,4 +45,4 @@ export declare const isSimpleRule: (rule: Rule) => rule is SimpleRule<any>;

export declare function useValidation<T>(formData: T & ValidateFormData<T>): {
form: UseValidation<T>;
onSubmit: (success: (formData: FormData<T>) => void) => void;
form: TransformedFormData<T>;
onSubmit: (success: (formData: FormData<T>) => void, errror?: (() => void) | undefined) => void;
add(pathToArray: (string | number)[], value: Record<string, unknown>): void;

@@ -54,0 +49,0 @@ remove(pathToArray: (string | number)[], index: number): void;

@@ -82,5 +82,8 @@ import { reactive, watch } from 'vue';

form: reactiveFormData,
onSubmit: (success) => {
onSubmit: (success, errror) => {
form.validateAll().then(hasError => {
if (!hasError) {
if (hasError) {
errror === null || errror === void 0 ? void 0 : errror();
}
else {
const resultFormData = {};

@@ -87,0 +90,0 @@ getResultFormData(reactiveFormData, resultFormData);

@@ -81,2 +81,4 @@ import { isSimpleRule } from './composable/useValidation';

this.simpleValidators.delete(uid);
console.log(this.simpleValidators);
console.log(this.keyedValidators);
}

@@ -83,0 +85,0 @@ getValidatorsFor(keys) {

{
"name": "vue3-form-validation",
"version": "2.0.1",
"version": "2.0.2",
"description": "Form validation for Vue 3",

@@ -5,0 +5,0 @@ "author": {

@@ -1,9 +0,8 @@

# (WIP) Form validation for Vue 3
Easy to use Form Validation for Vue 3
# Form validation for Vue 3
Easy to use opinionated Form validation for Vue 3.
* :milky_way: **Written in TypeScript**
* :ocean: **Dynamic Form support**
* :fallen_leaf: **Light weight**
Note this is still WIP! But a working prototype is currently available and can be used.
```bash

@@ -14,70 +13,125 @@ npm i vue3-form-validation

Validation is async and is utilising `Promise.allSettled`, [which](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) has not yet reached cross-browser stability.
Example usage can be found in this [Code Sandbox](https://codesandbox.io/s/vue-3-form-validation-demo-busd9).
## API
Currently this package exports two functions `provideBaseForm` and `useBaseForm`, plus some type definitions when using TypeScript (see `vue3-form-validation/composable/useForm.ts` for all exports).
This package exports one function `useValidation`, plus some type definitions for when using TypeScript.
Both functions are meant to be used inside of base form components. They make use of `provide` and `inject` to communicate data, which means that `provideBaseForm` has to be called in a component that is higher up in the tree than `useBaseForm`.
`SomeForm.vue`
``` html
<template>
<BaseForm> <-- provideBaseForm()
<BaseInput /> <-- useBaseForm()
<BaseSelect /> <-- useBaseForm()
</BaseForm>
</template>
### useValidation
```ts
const { form, add, remove, onSubmit } = useValidation<T>(formData)
```
### provideBaseForm
``` ts
const { onSubmit } = provideBaseForm();
```
* `useValidation` takes the following parameters:
* `provideBaseForm` exposes the following methods:
Parameters | Type | Required | Description
---|:-:|:-:|---
formData | `object` | `true` | The structure of your Form data.
Signature | Returns | Description
:-:|:-:|---
`onSubmit()` | `Promise<boolean>` | Call this when submitting the form. It validates all fields and returns a boolean value that indicates whether or not there are errors.
The `formData` object has a structure that is similar to any other object you would write for `v-model` data binding. The only difference being that for every value you can provide rules to display validation errors.
### useBaseForm
``` ts
const { uid, onBlur, errors, validating } = useBaseForm(modelValue, rules);
Let's look at an example how the structure of some `formData` object, can be converted to an object with the addition of rules:
```ts
const formData = {
name: '',
email: '',
password: ''
}
// The above can be converted to the following
const formDataWithRules = {
name: {
value: '',
rules: [name => !name && 'Name is required']
},
email: {
value: '',
rules: [email => !email && 'E-Mail is required']
},
password: {
value: '',
rules: [pw => pw.length > 7 || 'Password has to be longer than 7 characters']
}
}
```
* `useBaseForm` takes the following parameters:
The `formData` object can either be flat or nested by using arrays. The type definition for some Form field looks like the following:
Parameters | Type | Required | Description
---|:-:|:-:|---
modelValue | `Ref<unknown>` | `true` | A `ref` that holds the current form field value.
rules | `Ref<(function \| object)[]>` | `true` | A `ref` with an array of rules.
```ts
type Field<T> = {
value: Ref<T> | T;
rules?: Rule<T>[];
};
```
* `useBaseForm` exposes the following state:
To get the best IntelliSense while writing the `useValidation` function, it's recommended to define the structure of your `formData` upfront and pass it as the generic paramter. If at some point the provided type does not fit the required structure, it will let you know by converting the problematic part to be of type `never`. The type for the example above is pretty straightforward:
```ts
interface FormData {
name: Field<string>;
email: Field<string>;
password: Field<string>;
}
```
* `useValidation` exposes the following state:
State | Type | Description
---|:-:|---
uid | `number` | Unique id of the form field.
errors | `Ref<string[]>` | Validation errors.
validating | `Ref<boolean>` | `True` while atleast one rule is validating.
form | `object` | Transformed `formData` object, with added metadata for every Form field.
* `useBaseForm` exposes the following methods:
`Form` is a reactive object with identical structure as the `formData` input, but with added metadata to every Form field.
Signature | Returns | Description
:-:|:-:|---
`onBlur()` | `void` | Call this when the form field `blur` event fires.
**Typing:**
```ts
type TransformedField<T> = {
uid: number;
value: T;
errors: string[];
validating: boolean;
onBlur(): void;
};
// The type of form in the example above would be
const form: {
name: TransformedField<string>;
email: TransformedField<string>;
password: TransformedField<string>;
}
```
Key | Value | Description
---|:-:|---
uid | `number` | Unique identifier of the Form field. For dynamic Forms this can be used as the `key` attribute in `v-for`.
value | `T` | The value of the Form field which is meant to be used together with `v-model`.
errors | `string[]` | Array of validation error messages.
validating | `boolean` | `True` while atleast one rule is validating.
onBlur | `function` | Function that will mark this Form field as touched. After a Form field has been touched it will validate all rules after every input. Before it will not do any validation.
* `useValidation` exposes the following methods:
Signature | Parameters | Description
--- | :-: | ---
`onSubmit(success, failure?)` | | When this function is called it will validate all registered fields. It takes two parameters, a `success` and an optional `failure` callback.
|| `success` | Success callback which will be executed if there are no validation errors. Receives the `formData` as it's first argument.
|| `failure?` | Failure callback which will be executed if there are validation errors. Receives no arguments.
`add(pathToArray, value)` || Utility function for writing dynamic Forms. It takes two parameters, a `pathToArray` of type `(string \| number)[]` and a `value`.
|| `pathToArray` | An array of `string` and `numbers` representing the path to an array in the `formData`.
|| `value` | The `value` that will be pushed to the array at the given path.
`remove(pathToArray, index)` || Identical to `add` but instead of providing a `value` you provide an `index` that will be removed.
At the time there is no good IntelliSense support for the `add` and `remove` functions. When TypeScript 4.1 will be released and Vue supports it, this can be changed however. Also there are currently no online usage examples, you can however clone this repository to your local machine and run `npm run dev`, which will start a development server with an example site.
## Writing Rules
Rules are `async` functions that should return a `string` when the validation fails. They can be written purely as a function or together with a `key` property in an object.
Rules are functions that should return a `string` when the validation fails. They can be written purely as a function or together with a `key` property in an object.
They can also alternatively return a promise when you have a rule that requires asynchronous code.
**Typing:**
```ts
type SimpleRule = (value: unknown) => Promise<unknown>;
type KeyedRule = { key: string; rule: SimpleRule };
type Rule = SimpleRule | KeyedRule;
type SimpleRule<T = any> = (value: T) => Promise<unknown> | unknown;
type KeyedRule<T = any> = { key: string; rule: SimpleRule<T> };
type Rule<T = any> = SimpleRule<T> | KeyedRule<T>;
```
For now rules are meant to be passed as `props` to your base form components, where you then use them as a parameter for `useBaseForm`. KeyedRules that share the same key will be executed together, this can be useful in a situation where rules are dependent on another. For example the `Password` and `Repeat password` fields in a Login Form.
Keyed rules that share the same key will be executed together, this can be useful in a situation where rules are dependent on another. For example the `Password` and `Repeat password` fields in a Login Form.
Rules will always be called with the latest `modelValue`, to determine if a call should result in an error, it will check if the rule's return value is of type `string`.
`vue3-form-validation/Form.ts`
`main/Form.ts`
```ts

@@ -96,6 +150,18 @@ let error: unknown;

```ts
const required = async value => !value && "This field is required";
const min = async value => value.length > 3 || "This field has to be longer than 3 characters";
const max = async value => value.length < 7 || "This field is too long (maximum is 6 characters)";
const required = value => !value && 'This field is required';
const min = value => value.length > 3 || 'This field has to be longer than 3 characters';
const max = value => value.length < 7 || 'This field is too long (maximum is 6 characters)';
// Async rule
const isNameTaken = name =>
new Promise(resolve => {
setTimeout(() => {
if (['foo', 'bar'].includes(name)) {
resolve();
} else {
resolve('This name is already taken');
}
}, 2000);
})
```
Of course you can also return a `Promise` directly or perform network requests, for example checking if a username already exists in the database.
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc