Migrate from Vuelidate
Migrating from Vuelidate is really simple. Regle API is similar to Vuelidate's one on purpose, so the mental model stays the same.
Regle type safety will ensure you make no mistakes while making the migration.
Imports
ts
import { useVuelidate } from '@vuelidate/core';
import { required } from '@vuelidate/validators';
import { useRegle } from '@regle/core';
import { required } from '@regle/rules';
Helpers
ts
import { helpers } from '@vuelidate/validators';
import { withMessage, withParams, withAsync, isEmpty, ... } from '@regle/rules';
Helpers which have been renamed:
req
->isFilled
len
->getSize
regex
->matchRegex
forEach
-> Deleted, you can use$each
directly.unwrap
-> usetoValue
from Vue- Parameters are automatically unwrapped when using
createRule
- Parameters are automatically unwrapped when using
withMessage
Order of parameters are swapped
ts
const rule = helpers.withMessage('This field cannot be empty', required)
const rule = withMessage(required, 'This field cannot be empty')
withParams
You can create rules with parameters with createRule helper
ts
const contains = (param) =>
helpers.withParams(
{ type: 'contains', value: param },
(value) => !helpers.req(value) || value.includes(param)
)
const contains = createRule({
validator(value: Maybe<string>, param: Maybe<string>) {
return isEmpty(value) && value.includes(param);
},
message: ({$params: [param]}) => `Value must contain ${param}`;
})
Properties
Some properties have been renamed
$model
->$value
$response
->$metadata
Using metadata from rules$externalResults
->$externalErrors
Accessing nested fields
Nested fields are not mixed up with other properties now.
ts
v$.nested.child
r$.$fields.nested.$fields.child
Collections
ts
const v$ = useVuelidate({
collection: {
$each: helpers.forEach({
name: {
required
}
})
}
}, {collection: [{name: ''}]})
const { r$ } = useRegle({collection: [{name: ''}]}, {
collection: {
$each: {
name: {
required
}
}
}
})
Methods
ts
const result = await v$.$validate();
const {result, data} = await r$.$validate();
Validation groups
ts
const rules = {
number: { isEven },
nested: {
word: { required: v => !!v }
},
$validationGroups: {
firstGroup: ['number', 'nested.word']
}
}
const v$ = useVuelidate(rules, ...);
const { r$ } = useRegle(..., {
number: {isEven},
nested: {
word: { required: v => !!v }
}
}, {
validationGroups: (fields) => ({
firstGroup: [fields.number, fields.nested.$fields.word]
})
})
r$.$groups.firstGroup