验证iso日期,但使用日期选择器组件时显示区域设置日期

时间:2019-07-10 20:54:27

标签: vue.js vuetify.js

我想将日期选择器组件与本地化支持一起使用。我创建了这个日期选择器示例

HTML:

<div id="app">
  <v-app id="inspire">
  <v-menu 
    :value="showDatePicker" 
    max-width="290px"
  >
    <template v-slot:activator="{ on }">
      <v-text-field 
        :value="formattedDate"
        readonly 
        clearable
        label="Date"
        v-on="on"
        :rules="rules"
        :required="true"
        @input="selectDate"
      ></v-text-field>
    </template>
    <v-date-picker 
      :value="date" 
      :locale="currentLocale"
      no-title
      @input="selectDate"
    />
  </v-menu>
  </v-app>
</div>

JS:

new Vue({
  el: '#app',
  data: () => ({
    showDatePicker: false,
    date: '',
    currentLocale: 'de',
    rules: [
      value => this.validateDate(value) || 'Invalid date'
    ]
  }),
  computed: {
     formattedDate: function () {
       const formattedDate = this.date

       // !! format the date based on this.currentLocale !!

       return formattedDate
     }
  },
  methods: {
    selectDate: function(newDate) {
      this.showDatePicker = false;
      this.date = newDate;
    },
    validateDate: function(date){
      // !! validate iso date here !!

      return true
    }
  }
})

https://codepen.io/anon/pen/ydZqxd?editors=1010

日期选择器组件本身以iso格式返回日期。我想使用它,但我也想为用户显示区域设置日期格式。事情变得棘手,因为我想用iso格式验证日期,但文本字段使用格式化的日期作为其值。因此,在进行验证时,文本字段会传递格式化日期,但这是错误值。应该是iso日期。

具有显示/值之类的东西很酷,尽管对于文本字段没有意义...

是否可以将iso格式传递给验证规则并仅显示格式化日期?

1 个答案:

答案 0 :(得分:2)

U可以轻松完成。只需遵循以下代码:

new Vue({
    el: '#app',
    data: (vm) => ({
        showDatePicker: false,
        date: '',
        currentLocale: 'de',
        rules: [
            value => vm.validateDate(value) || 'Invalid date'
        ]
    }),
    computed: {
        formattedDate: function () {
            // !! format the date based on this.currentLocale !!
            let formattedDate = "";
            let options = {
                weekday: "short",
                year: "numeric",
                month: "2-digit",
                day: "numeric"
            }
            if (this.date) {
                formattedDate = new Date(this.date).toLocaleDateString(this.currentLocale, options)
            }
            return formattedDate
        }
    },
    methods: {
        selectDate: function (newDate) {
            this.showDatePicker = false;
            this.date = newDate;
        },
        validateDate: function (date) {
            // !! validate iso date here !!

            return true
        }
    }
});

1)有关选项和toLocaleDateString功能的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

2)我也修正了这一点:value => this.validateDate(value) || 'Invalid date'value => vm.validateDate(value) || 'Invalid date', because this not working in 'data',因为您需要传递vuejs实例

3)U可以为此行if (this.date)添加预匹配,以检查日期是否正确

测试:https://codepen.io/anon/pen/dBEjor?editors=1010