Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
vue3-form-validation
Advanced tools
Vue composition function for Form Validation with async rules.
npm install vue3-form-validation
This package exports one function useValidation
, plus some type definitions for when using TypeScript.
const { form, errors, submitting, validateFields, resetFields, add, remove } =
useValidation<T>(formData);
useValidation
takes the following parameters:formData
object
The form data object has a structure that is similar to any other object you would write for v-model
data binding. The only difference being that together with every value you can provide rules to display validation errors.
Let's look at an example how the structure of some form data object can be converted to an object with the addition of rules:
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'
]
}
};
The form data object can contain arrays and can be deeply nested. At the leaf level, the object should contain fields whose simplified type definition looks like the following:
type Field<T> = {
$value: Ref<T> | T;
$rules?: Rule[];
};
To get better type inference while writing the useValidation
function, it's recommended to define the structure of your data upfront and pass it as the generic parameter T
. The type for the example above is pretty straightforward:
type FormData = {
name: Field<string>;
email: Field<string>;
password: Field<string>;
};
const { ... } = useValidation<FormData>({ ... });
useValidation
exposes the following state:form
object
submitting
Ref<boolean>
True
during validation after calling validateFields
.errors
ComputedRef<string[]>
Form
is a reactive object with identical structure as the form data input
but with added metadata to every field.
Every object with a $value
property will be converted to an object of the following type:
type TransformedField<T> = {
$uid: number;
$value: T;
$errors: string[];
$hasError: boolean;
$validating: boolean;
$onBlur(): void;
};
Given the structure of the previous example, this will result in the following:
type Form = {
name: TransformedField<string>;
email: TransformedField<string>;
password: TransformedField<string>;
};
As you may have noticed, all of the properties are prefixed with the $
symbol, which is to distinguish them from other properties but also to avoid naming conflicts. Below is a description of all the properties and their use case:
$uid
number
key
attribute in v-for
.$value
T
modelValue
of the field, which is meant to be used together with v-model
.$errors
string[]
$hasError
boolean
True
while there are validation errors.$validating
boolean
True
while at least one rule is validating.$onBlur
function
useValidation
exposes the following methods:validateFields(names?: any[]) -> Promise
names?
- Field names to validate.Promise
which will reject if there are validation errors, and resolve with the form data otherwise. Will throw ValidationError
which you can compare against using instanceof
.resetFields(formData?: object) -> void
formData?
- Values to use when resetting (see Sandbox examples).add(path: (string | number)[], value: any) -> void
path
- The path of the property to add.value
- The value to add (fields will be transformed as shown above).remove(path: (string | number)[]) -> void
path
- The path of the property to remove. For example remove(['as', 0])
will remove the first element in an array called as
at the root level.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:
type SimpleRule<T = any> = (value: T) => any;
type KeyedRule = {
key: string;
rule?: (...values: any[]) => any;
};
type Rule<T = any> = SimpleRule<T> | KeyedRule;
Keyed rules that share the same key
will be executed together. This can be useful in a situation where rules are dependent on another, such as the Password
and Confirm Password
fields in a Signup Form.
Rules will always be called with the latest modelValue
.
Simple rules will only receive their own argument, whereas keyed rules will also receive every other modelValue
with a matching key.
To prevent overly aggressive error messages, keyed rules will only be called after all fields with connected rules have been touched.
To determine if a call should result in an error, it will check if the rule's return value is of type string
. This way, many basic rules can be written in one line:
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 rules allow you to perform network requests, for example checking if a username exists in the database. The same principle applies as for synchronous rules, resolve
or reject
with a string if the validation fails:
const isNameTaken = name =>
new Promise(resolve => {
setTimeout(() => {
if (['Alice', 'Bob'].includes(name)) {
resolve();
} else {
resolve('This name is already taken');
}
}, 2000);
});
If you find problems or if you have use cases that you think are not easy to achieve with the current API, please let me know :+1: Feel free to write an issue or open a pull request, for more information about the project check out the contributing guideline.
FAQs
Vue composition function for form validation
The npm package vue3-form-validation receives a total of 168 weekly downloads. As such, vue3-form-validation popularity was classified as not popular.
We found that vue3-form-validation demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.