moses toh
moses toh

Reputation: 13192

Why required not working in vue.js 2?

You can see my case below

My vue component is like this :

<template>
    <select class="form-control" :name="elementName" v-model="selected" :required="module === 'addProduct'" >
        <option>Choose</option>
        <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
    </select>
</template>
<script>
    ...
    export default {
        ...
        props: ['elementName', 'module'],
        data() {
            return {
                selected: 'Choose'
            };
        },
        ...
    };
</script>

The result is like this :

enter image description here

I don't select anything. I click button submit, the required not working. It not display the required

I try like this :

<option value="">Choose</option>

It works. But, when accessed first time, option choose not show

How can I solve this problem?

Upvotes: 0

Views: 1736

Answers (1)

XCS
XCS

Reputation: 28177

See their example: https://v2.vuejs.org/v2/guide/forms.html#Select

It doesn't display anything because you have: selected: 'Choose' but you have no option with value="Choose". (the value is the empty string, "Choose" is just the inner text of the option element).

Try this:

<template>
    <select class="form-control" :name="elementName" v-model="selected" :required="module === 'addProduct'" >
        <option disabled value="">Choose</option>
        <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
    </select>
</template>
<script>
    ...
    export default {
        ...
        props: ['elementName', 'module'],
        data() {
            return {
                selected: ''
            };
        },
        ...
    };
</script>

Upvotes: 1

Related Questions