VueJS Element-UI el-date-picker 自定义验证

VueJS Element-UI el-date-picker custom validation

我正在使用 Element-UI date picker,我想在我的服务器验证所选日期是否有效后设置自定义验证。

<div class="form-row">
    <label class="form-label" for="date">Date</label>
    <el-date-picker class="NewReminder__date-picker"
        v-model="dateobj"
        type="date">
    </el-date-picker>
</div>

Any clue on how to do that? Apprecaite

您可以使用 Element UI Guide: Custom Form Validation Rule

查看上面指南中的演示

您需要创建一个规则, 然后在规则处理程序中,如果成功则调用 callback(),如果服务器响应验证结果失败则调用 callback(new Error('something...')),.

或以下 fiddle 是一个实现自定义验证器的示例,它使用一个观察器来实现它。

new Vue({
  el: "#app",
  data () {
    return {
    dateobj: null,
    hasError: false,
    loading: false
    }
  },
  watch: {
    dateobj: function (newVal) {
      this.loading = true
      this.hasError = false
      setTimeout(()=>{
        this.hasError = Math.random() > 0.5 ? true : false
        this.loading = false
      }, 1500)
    }
  }
})
@import url("//unpkg.com/element-ui@2.4.6/lib/theme-chalk/index.css");
.my-error {
  background-color:red;
  color:white;
}
.lds-circle {
  display: inline-block;
  background: gray;
  animation: lds-circle 2.4s cubic-bezier(0, 0.2, 0.8, 1) infinite;
}
@keyframes lds-circle {
  0%, 100% {
    animation-timing-function: cubic-bezier(0.5, 0, 1, 0.5);
  }
  0% {
    transform: rotateY(0deg);
  }
  50% {
    transform: rotateY(1800deg);
    animation-timing-function: cubic-bezier(0, 0.5, 0.5, 1);
  }
  100% {
    transform: rotateY(3600deg);
  }
}
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.4.6/lib/index.js"></script>
<div id="app">
<div class="form-row">
    <label class="form-label" for="date">Date</label>
    <el-date-picker class="NewReminder__date-picker" 
        v-model="dateobj"
        type="date"
        :readonly="loading">
    </el-date-picker>
    <span class="my-error" v-if="hasError">the server return one error</span>
    <span class="lds-circle" v-if="loading">loading</span>
</div>
</div>