Rule wrappers
Rule wrappers let you customize or upgrade your rules by injecting or replacing some properties.
Built-in wrappers
withMessage
The withMessage wrapper lets you associate an error message with a rule. Pass your rule as the first argument and the error message as the second.
import { } from '@regle/rules';
const = ((: <string>) => ({
: === 'regle',
: 'bar' as
})) satisfies ;
const { } = ({ : '' }, {
: {
// Inline functions can be also written... inline
: ((: <string>) => !!, "Custom Error"),
: (, "Custom Error"),
// You can also access the current value and metadata with a getter function
: (
,
({ , }) => `Custom Error: ${} ${}`
),
}
})Every error can be accessed in the r$ object. In either $errors (if the field is dirty) or $silentErrors properties.
In this case:
r$.$errors.namer$.name.$errors
withParams
The withParams wrapper allows your rule to depend on external parameters, such as a reactive property in your component or store.
By default, useRegle observes changes automatically when rules are defined using getter functions or computed properties.
/** Non reactive rules */
useRegle({}, { /* rules */})⬇️
useRegle({}, () => ({ /* rules */ }))
// or
const rules = computed(() => ({/* rules */ }))
useRegle({}, rules)However, sometimes dependencies cannot be tracked automatically, use withParams to manually define them:
import { } from '@regle/rules';
const = ('foo');
const { } = ({ : '' }, {
: {
: ((, ) => === , []),
// or
: ((, ) => === , [() => .]),
}
})withAsync
withAsync works like withParams, but is specifically designed for async rules that depend on external values.
import { withAsync } from '@regle/rules';
const base = ref('foo');
const { r$ } = useRegle({ name: '' }, {
name: {
customRule: withAsync(async (value, param) => {
await someAsyncCall(param)
}, [base])
}
})withTooltip
The withTooltip wrapper allows you to display additional messages for your field that aren’t necessarily errors.
Tooltips are aggregated and accessible via xxx.$tooltips.
import { withTooltip } from '@regle/rules';
const { r$ } = useRegle({ password: '' }, {
password: {
strong: withTooltip(
(value) => !!value && value.length >= 8,
'Password should be at least 8 characters'
),
}
})
// Access tooltips in template: r$.password.$tooltipsChaining wrappers
You can combine multiple wrappers to create more powerful and flexible rules while keeping everything typed correctly.
import { , } from '@regle/rules';
const = (1);
const { } = ({ : '' },
{
: {
: (
(
async (, ) => await (),
[]
),
({, : [] }) => `Custom error: ${} != ${}`
),
},
}
);
