Vuetify how to mark field as required

核能气质少年 提交于 2019-11-29 14:43:57

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).

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>

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!