Vuetify how to mark field as required

2020-02-13 10:31发布

When we try to fill forms in the internet, required fields are marked using a red color ' * ' mark to indicate that the field is a must.

Like that is there a way to indicate users to required fields in vuetify.js?

4条回答
手持菜刀,她持情操
2楼-- · 2020-02-13 10:45

From v1.1.0 docs:

The required prop no longer explicitly adds an asterisk to the label. All of its functionality to validation was removed for v1.0.

So apparently nothing will set it as required anymore, we have to add it manually in the label:

label="Name*"

Or you could use CSS:

.required label::after {
    content: "*";
}

Tho you must add required class manually (name of the class is arbitrary of course).

查看更多
叛逆
3楼-- · 2020-02-13 11:00

Performance wise, I don't know if this is the best solution. But it works.

Import the JavaScript file bellow into you application bootstrap (or something like that).

import Vue from 'vue';

Vue.mixin({
    mounted() {
        const e = this.$el;

        if ('querySelector' in this.$el) {
            const i = this.$el.querySelector('input[required]');

            if (i !== null) {
                const l = i.previousSibling;

                if (l.querySelector('.required.sign') === null) {
                    const r = document.createElement('span');

                    // l.classList.add('required');
                    r.classList.add('required', 'sign');

                    r.appendChild(document.createTextNode('*'));
                    l.appendChild(r);
                }
            }
        }
    },
});

Nuxt.js: put the file above into the plugins folder. Include its path on the plugins array on the nuxt.config.js file.

Add the rule bellow to your global CSS / theme.

.v-label  > .required.sign {
    color: darkred;
    font-weight: bold;
    margin-left: .25em;
}
查看更多
神经病院院长
4楼-- · 2020-02-13 11:05

You are able to pass a rules prop to a v-text-field.

E.g,

<v-text-field
  v-model="title"
  :rules="['Required']"
  label="Title"
  counter
  maxlength="20"
></v-text-field>

See this Vuetify example for a fuller picture: https://github.com/vuetifyjs/vuetifyjs.com/blob/master/src/examples/text-fields/validation.vue

required is also an HTML property. You could just add it to the HTML Element like this:

<v-text-field
  v-model="title"
  label="Title"
  counter
  maxlength="20"
  required
></v-text-field>
查看更多
倾城 Initia
5楼-- · 2020-02-13 11:07

It's a bit of a pain, but there is a 'label' named slot and you can do something like this:

<v-text-field
    v-model="loginInfo.email"
    autofocus
    name="email"
    type="email">
  <template #label>
    <span class="red--text"><strong>* </strong></span>Email
  </template>
</v-text-field>
查看更多
登录 后发表回答