-
Notifications
You must be signed in to change notification settings - Fork 3
Documentation
Install vue3-form-validation
with your favorite package manager:
yarn add vue3-form-validation
# or with npm
npm install vue3-form-validation
Configure the validation through createValidation
and pass it to the app:
import { createValidation } from 'vue3-form-validation'
const validation = createValidation({
defaultValidationBehavior: 'lazier',
validationBehavior: {}
})
app.use(validation)
Start using useValidation
in your components.
At its core, this package exports one function useValidation
, plus some type definitions for when using TypeScript.
import { useValidation } from 'vue3-form-validation'
const {
form,
submitting,
validating,
errors,
hasError,
validateFields,
resetFields,
add,
remove
} = useValidation({})
-
formData
{object}
The structure of yourformData
FormData
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 property, you can provide rules to display validation errors. Let's look at an example:
const formData = {
email: '',
password: ''
}
The above can be converted to the following:
const formData = {
email: {
$value: '',
$rules: [email => !email && 'Please enter your email address']
},
password: {
$value: '',
$rules: [
password =>
password.length > 7 || 'Password has to be longer than 7 characters'
]
}
}
FormData
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: T | Ref<T>
$rules?: Rule<T>[]
}
-
form
{object}
A transformedformData
object -
submitting
{Ref<boolean>}
True
during validation after callingvalidateFields
when there were rules that returned aPromise
-
validating
{ComputedRef<boolean>}
True
while the form has any pending rules -
errors
{ComputedRef<string[]>}
All current validation error messages -
hasError
{ComputedRef<boolean>}
True
if the form has any error
Form
is a reactive object with identical structure as the formData
input but with added metadata to every field. All objects with a $value
are converted to an object of the following type:
type TransformedField<T> = {
$uid: number
$value: T
$errors: string[]
$rawErrors: (string | null)[]
$hasError: boolean
$validating: boolean
$touched: boolean
$dirty: boolean
$validate(options?: ValidateOptions): void
}
Given the data of the previous example, this would result in the structure below:
type Form = {
email: TransformedField<string>
password: TransformedField<string>
}
Listed as follows are descriptions of all the properties and their use case:
-
$uid
{number}
The unique id of this field. For dynamic forms, this can be used as thekey
attribute inv-for
-
$value
{any}
The current field's value. Intended to be used together withv-model
-
$errors
{string[]}
A list of validation error messages local to this field withoutnull
values -
$rawErrors
{(string | null)[]}
The field's raw error messages one for each rule andnull
if there is no error -
$hasError
{boolean}
True
while there are any errors on this field -
$validating
{boolean}
True
while the field has any pending rules -
$touched
{boolean}
True
if the field is touched. In most cases, this value should be set together with theblur
event. Either through$validate
or manually -
$dirty
{boolean}
True
if the$value
of this field has changed at least once -
$validate
{function}
Validate this field
Validate the rules of this field.
-
options
{object}
Options to use for validation-
setTouched
{boolean}
Set the field touched when called- Default
true
- Default
-
force
{boolean}
Validate with theforce
flag set- Default
true
- Default
-
- Returns:
{void}
Validate all fields.
-
options
{object}
Options to use for validation.-
names
{string[]}
A list of field names to validate. Names are taken from the properties in theformData
- Default
undefined
Meaning validate all
- Default
-
predicate
{function}
A filter function to determine which values to keep in the resultingformData
. Used likeArray.prototype.filter
but for objects- Default
() => true
Meaning keep all
- Default
-
- Returns:
{Promise}
APromise
containing the resultingformData
- Throws:
{ValidationError}
AnError
when there were any failing rules
-
iteratorResult
{object}
-
key
{string}
The current key -
value
{any}
The current value -
path
{string[]}
The current path in the object
-
- Returns:
{any}
Return anything ortrue
if the value should be kept
Reset all fields to their default value or pass an object to set specific values.
-
formData
{ object }
FormData
to set specific values. It has the same structure as the object passed touseValidation
- Default
undefined
Meaning use the default values
- Default
It will not create any new fields that are not present in the formData
initially.
Adds a new properties to the formData
.
-
path
{(string | number)[]}
A path where the new data is added -
value
{any}
The data to add
Objects with a $value
property are transformed, as seen above.
Removes a property from the formData
.
-
path
{(string | number)[]}
The path of the property to remove
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 return a Promise
when you have a rule that requires asynchronous code:
const { form } = useValidation({
name: {
$value: '',
// Here we use a simple rule.
// If name does not contain a value it will return the error message.
$rules: [name => name.length === 0 && 'Please enter your name']
},
password: {
$value: '',
// Here we use a keyed rule. Keyed rules will be executed together.
// As arguments it will receive both password as well as confirmPassword
// because they share the same key value (pw).
// If both do not match return the error message.
$rules: [
{
key: 'pw',
rule: (password, confirmPassword) =>
password !== confirmPassword && 'Passwords do not match'
}
]
},
confirmPassword: {
$value: '',
$rules: [
{
key: 'pw',
rule: (password, confirmPassword) =>
password !== confirmPassword && 'Passwords do not match'
}
]
}
})