The toType
, toValidableType
, and fromType
functions can be used to create custom standalone validators. In fact, they are used internally by vue-types
in native and custom validators.
In the following example, we define a validator for positive numbers:
tsconst positive = () =>
toType('positive', {
type: Number,
validator: (v) => v >= 0,
})
export default {
props: {
myNumber: positive().isRequired,
},
}
Both toType
and toValidableType
accept the following arguments:
name
string The validator name, used for logging type
object An object compatible with Vue.js prop validation
TIP
The difference between toType
and toValidableType
is that the latter creates validators that support the .validate()
method to set up custom validation logic.
To promote code reusability and composability, you can use fromType
to reuse an existing validator or validator instance as a base for a new validator.
Function arguments:
name type required descriptionname
string yes The validator name, used for logging source
validator yes Source prop validator props
object - Custom validation properties
Example:
jsimport { fromType, shape, number, string } from 'vue-types'
const user = shape({
ID: number(),
name: string(),
})
// Clone the user shape and make it required
const userRequired = fromType('userRequired', user, { required: true })
WARNING
Properties defined in the third argument overwrite those specified in the base validator.
The only exception is validator()
: these functions are and executed in sequence until one returns false
.
import { fromType, shape, number, string } from 'vue-types'
const userRequired = shape({
ID: number(),
name: string(),
}).isRequired
// `userJohn` is not required.
// After validating the shape, it ensures that `name === 'John'`.
const userJohn = fromType('userJohn', user, {
required: false,
validator(value) {
return value.name === 'John'
},
})
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4