验证 ISO 日期,但在使用日期选取器组件时显示区域设置日期



我想使用具有本地化支持的日期选择器组件。我创建了这个日期选择器示例

.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 格式传递给验证规则并显示格式化日期?

你可以很容易地做到。只需遵循以下代码:

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(您可以为此行添加怀孕匹配if (this.date)以检查正确的日期

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

最新更新