CodexBloom - Programming Q&A Platform

Form Validation Not Triggering on Custom Input Component in Vue 3

πŸ‘€ Views: 69 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-24
vue vue3 form-validation JavaScript

This might be a silly question, but I'm working on a form in Vue 3 that includes a custom input component... The form is supposed to validate user input before submission, but it seems like the validation logic is not being triggered when I use my custom component. I have the following setup: ```vue <template> <form @submit.prevent="handleSubmit"> <custom-input v-model="formData.username" :rules="usernameRules" /> <span v-if="errors.username">{{ errors.username }}</span> <button type="submit">Submit</button> </form> </template> <script> import CustomInput from './CustomInput.vue'; export default { components: { CustomInput }, data() { return { formData: { username: '', }, errors: {}, usernameRules: [ value => !!value || 'Username is required', value => (value && value.length >= 3) || 'Username must be at least 3 characters', ], }; }, methods: { handleSubmit() { this.errors = {}; const validationResults = this.usernameRules.map(rule => rule(this.formData.username)); const invalidRules = validationResults.filter(result => result !== true); if (invalidRules.length > 0) { this.errors.username = invalidRules[0]; return; } // proceed with form submission }, }, }; </script> ``` In the `CustomInput` component, I emit an event on input change: ```vue <template> <input :value="modelValue" @input="updateValue" /> </template> <script> export default { props: ['modelValue'], methods: { updateValue(event) { this.$emit('update:modelValue', event.target.value); }, }, }; </script> ``` The question I'm working with is that the validation logic runs but does not catch the username field when it’s empty; it always returns `undefined` instead of the behavior message. I’ve verified that the `v-model` binding is correct, but the validation only seems to check the initial state of the `formData.username` and not its actual current value during submission. I've tried console logging the values during validation, and they appear correct, but the behavior messages are never set. Has anyone faced a similar scenario, or could someone point out what I'm doing wrong here? I recently upgraded to Javascript 3.10. My development environment is Ubuntu 20.04. What's the correct way to implement this?