Way to restrict date picker to only accept numbers and hyphens, and restrict other values ​​in Vue
P粉729518806
P粉729518806 2023-08-26 14:57:04
0
1
620
<p>I am using vue2-datepicker npm package to handle dates. Date input accepts all letters, numbers and special characters. But I want the input to only accept numbers, hyphens and slashes. I can easily achieve this using normal html input. But how to implement it in date picker? Any help would be greatly appreciated. Thanks in advance</p> <p>The npm link I'm using. </p> <p>Shows an image of an input field accepting different values. </p> <p>Here are the tags and attributes I'm using. </p> <pre class="brush:php;toolbar:false;"><date-picker :placeholder="fieldItem.name" v-model="fieldItem.value" format="MM-DD-YYYY" v-if="fieldItem.type == 'datePicker'" type="number" ></date-picker></pre>
P粉729518806
P粉729518806

reply all(1)
P粉023650014

You can use scope slots to achieve this:

<date-picker
  format='MM-DD-YYYY'
  value-type='format'
  v-model='time'>
  <template #input='{ props, events }'>
    <input
      v-bind='props'
      v-on='events'>
  </template>
</date-picker>

Now we can intercept input events and remove unwanted characters:

<date-picker
  format='MM-DD-YYYY'
  value-type='format'
  v-model='time'>
  <template #input='{ props, events }'>
  <input
    v-bind='props'
    v-on='{
      ...events,
      input: event => handleInput(event, events.input)
    }'>
  </template>
</date-picker>
...
  methods: {
    handleInput (event, update) {
      let value = event.target.value.replace(/[^0-9/-]/g, '')

      // 强制Vue在删除一些字符后刷新输入框
      this.$forceUpdate()

      // 将新值应用于让vue2-datepicker继续其流程
      update(value)
    }
  }
...

Example

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template