I have a requirement for two fields named "price" and "max_price". Whenever I modify the "price" field, I need a validator to trigger the lessThanMaxPrice validation rule.
Currently, everything is functioning as expected with this setup:
<script setup lang="ts">
const lessThanMaxPrice = (price: number) => {
const maxPrice = editItemForm.max_price;
let isValid = true;
if (price || maxPrice) {
if (!maxPrice) {
isValid = false;
} else if (price && price >= maxPrice) {
isValid = false;
}
}
return isValid;
};
const editItemRules = computed(() => {
return {
price: {
lessThanMaxPrice: helpers.withMessage(t('validation_errors.price_error'), lessThanMaxPrice),
},
}
});
let editItemForm = reactive({
price: number|null,
max_price: number|null
});
const editItemV$ = useVuelidate(editItemRules, editItemForm);
</script>
<template>
<v-text-field variant="outlined" hide-details="auto" id="p" type="number"
:valid="editItemV$.price.$error" :color="editItemV$.price.$error ? 'success' : ''"
:error-messages="editItemV$.price.$error ? editItemV$.price.$errors[0].$message.toString() : ''"
step="0.01" @change="editItemV$.price.$touch" v-model="editItemForm.price" />
<v-text-field variant="outlined" hide-details="auto" id="max_price" type="number"
:valid="editItemV$.max_price.$error" :color="editItemV$.max_price.$error ? 'success' : ''"
:error-messages="editItemV$.max_price.$error ? editItemV$.max_price.$errors[0].$message.toString() : ''"
step="0.01" @change="editItemV$.max_price.$touch" v-model="editItemForm.max_price" />
</template>
Now, my goal is to move the lessThanMaxPrice function into a ValidationHelpers class so that it can be used in other components as well:
export class ValidationHelpers {
static lessThanMaxPrice(price: number | null, maxPrice: number | null) {
let isValid = true;
if (price || maxPrice) {
if (!maxPrice) {
isValid = false;
} else if (price && price >= maxPrice) {
isValid = false;
}
}
return isValid;
};
}
I am struggling with how to call the ValidationHelpers.lessThanMaxPrice function with parameters. The following method is not working:
const editItemRules = computed(() => {
return {
price: {
lessThanMaxPrice: (value) => helpers.withMessage(t('validation_errors.price_error'), ValidationHelpers.lessThanMaxPriceTest(value, editItemForm.max_price)),
}
}
});
An error is thrown by VSCode:
Argument of type 'boolean' is not assignable to parameter of type 'ValidationRule<unknown>'.ts(2345)
As I'm new to Vue / Vuelidate / Vuetify / TypeScript, your understanding and guidance are highly appreciated :)