Extensible, lightweight validation library for Vue
View the documentation for a complete guide, including examples and API reference.
Starting from version 1.0.6, this library supports both Vue 3 and Vue 2 + Composition API. Earlier versions support only Vue 3.
# install with npm
npm install vue-validus --save
# install with yarn
yarn add vue-validus --save
Below is a simple example of one approach for leveraging vue-validus for validation, for more detailed examples and additional approaches, please visit the documentation. This example will use Vue refs as the source for the field values, though you could also use a reactive object or just the fields themselves without separate value properties.
import { defineComponent, ref } from 'vue'
import { field, fieldGroup, required } from 'vue-validus'
export default defineComponent({
setup() {
// example: field group containing fields with values sourced from refs
const username = ref('')
const password = ref('')
const form = fieldGroup({
username: field([required()], username),
password: field([required()], password)
})
// example: validate entire group at once and check result
const handleSubmit = () => {
form.validate()
if (!form.invalid) {
// submit...
}
}
return { username, password, form, handleSubmit }
}
})
At this point, since our field values are backed by refs, you could set an input's v-model attribute to either username
or form.username.value
, both will maintain the same value between them.
<input type="text" v-model="username" @blur="form.username.validate()" />
<!-- check if field is invalid and display error messages -->
<span v-if="form.username.invalid">{{ form.username.errorMessages }}</span>
<!-- or check if field has specific error -->
<span v-if="form.username.hasError('required')">Username is required</span>
<!-- password input omitted for brevity, works the same as username input -->
It is recommended to define your validation field & field groups within the component's setup
function as demonstrated in the above Composition API example. However, if needed, you can define these within the Options API's data
structure.
import { defineComponent } from 'vue'
import { field, fieldGroup, required } from 'vue-validus'
export default defineComponent({
data() {
return {
form: fieldGroup({
username: field([required()], '<optional initial value>'),
password: field([required()])
})
}
}
})
<input
type="text"
v-model="form.username.value"
@blur="form.username.validate()"
/>
<!-- check if field is invalid and display error messages -->
<span v-if="form.username.invalid">{{ form.username.errorMessages }}</span>
<!-- or check if field has specific error -->
<span v-if="form.username.hasError('required')">Username is required</span>
<!-- password input omitted for brevity, works the same as username input -->
Changes for each release are documented in the CHANGELOG file.
This project is licensed under the MIT License - see the LICENSE file for details.