A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://vue-types.codeful.dev/advanced/custom-validators.html below:

Website Navigation


Custom validators | VueTypes

Custom validators

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.

Custom validators from scratch

In the following example, we define a validator for positive numbers:

ts
const positive = () =>
  toType('positive', {
    type: Number,
    validator: (v) => v >= 0,
  })

export default {
  props: {
    myNumber: positive().isRequired,
  },
}

Both toType and toValidableType accept the following arguments:

name type description 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.

Composing existing validators

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 description name string yes The validator name, used for logging source validator yes Source prop validator props object - Custom validation properties

Example:

js
import { 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.

js
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