Search code examples
vue.js

Form Validation not working in custom component Vue


Vue 3.4.21

I have a form and when I add elements to it without using a custom component, validation works:

   <div class="form-group element">
          <input type="text" :name="name" class="form-control" placeholder=" "
            required pattern="([\w]{2,})" />
          <label :for='x.slug' class="form-control-placeholder">
            Name: 
          </label>
          <span class="error-msg">Please type at least 2 characters </span>
        </div>
      </div>

The error message appears as it's supposed to.

Now, I've created a custom component like so:

        <template>
            <div class="form-group element">
                <input type="text" :name="name" class="form-control :required='required'>
                <label :for='name' class="form-control-placeholder">
                    {{ name }}:
                </label>
                <span class="error-msg">{{ errorMsg }}</span>
            </div>
        </template>

        <script setup>

        import { toRefs } from 'vue'

        const props = defineProps({
            pattern: String,
            errorMsg: String,
            name: String,
            required: Boolean,
        })
        const { pattern, name, errorMsg, required } = toRefs(props);
        </script>

And I use it like this:

   <CustomInput
      :errorMsg="'Please write at least 2 characters'" 
      :required="true"
      :name="'name'"
      :pattern="'([\w]{2,})'"
    />

The error message appears even when I meet the criteria (typing at least 2 characters)

How do I make validation function correctly when passing in props to a custom component as opposed to hard coding them on the page?

Thanks


Solution

  • You have a lot of mistakes in the code, and the main thing in the key of the question is that you don't pass the pattern to the input component. I created a simple example for you where everything works.

    // App.vue
    
    <script setup>
    import Input from './Input.vue';
    </script>
    
    <template>
      <form>
        <Input
          :required="true"
          pattern="([\w]{2,})"
        />
        <button>Submit</button>
      </form>
    </template>
    
    // Input.vue
    
    <script setup>
    defineProps({
      type: String,
      name: String,
      required: Boolean,
      errorMsg: String,
      pattern: String
    })
    </script>
    
    <template>
      <div class="form-group element">
          <input
            :type="type"
            :name="name"
            :required="required"
            :pattern="pattern"
            class="form-control"
          >
          <label
            :for="name"
            class="form-control-placeholder"
          >
            {{ name }}
          </label>
          <span class="error-msg">{{ errorMsg }}</span>
      </div>
    </template>