Home  >  Q&A  >  body text

Way to restrict date picker to only accept numbers and hyphens, and restrict other values ​​in Vue

<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粉729518806P粉729518806388 days ago522

reply all(1)I'll reply

  • P粉023650014

    P粉0236500142023-08-27 00:21:48

    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

    reply
    0
  • Cancelreply