What is the best way to limit the date picker to only accept numbers and hyphens in the input field while blocking any other input in Vue?

I have been utilizing the vue2-datepicker npm package for handling dates. The date input currently accepts all alphabets, numbers, and special characters but I only want it to allow numbers, hyphens, and forward slashes. It's simple to achieve this using a regular HTML input field, but how can I implement this restriction in the date picker? Any assistance on this matter would be highly appreciated. Thank you in advance.

Here is the link to the npm package I am utilizing.

An image demonstrating the input field with various values being accepted.

Below are the tags and attributes I am employing:


        <date-picker
          :placeholder="fieldItem.name"
          v-model="fieldItem.value"
          format="MM-DD-YYYY"
          v-if="fieldItem.type == 'datePicker'"
          type="number"
        ></date-picker>

Answer №1

To achieve this, you can utilize scoped slots like so:

<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>

For a full list of available slots with vue2-datepicker, check out the documentation here.

Now, you can intercept the input event and eliminate unwanted characters by modifying the code as follows:

<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, '')

      // force Vue to refresh input after remove some characters
      this.$forceUpdate()

      // Apply new value to let vue2-datepicker continue its flow
      update(value)
    }
  }
...

Here's an example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Delay with Vue.js v-bind causing form submission to occur before the value is updated

Trying to update a hidden input with a value from a SweetAlert modal, but encountering issues. The following code isn't working as expected - the form submits, but the hidden field's value remains null. HTML: <input type="hidden" name="inpu ...

The for each loop fails to return the value

In my Vue component, I have a conditional loop that iterates through train stations with 'New York' as the destination or on the route. <tr v-for="departure in filterTrainStations" :key="departure.name"> <td>{{ departure. ...

Each time a page loads, the react useContext feature is causing the web socket connection to reset

I have integrated websockets into various parts of my nextJS application and need to make sure they are accessible everywhere without resetting the socket connection. Whenever the connection is reset, it loses all the rooms it was connected to, causing iss ...

How can I create a blank line in Vue once an option is selected?

When using the dropdown menu with 3 selections, I want to ensure that the choice "Choice1" is not displayed at all. Instead of showing any text, it should just display as an empty line if you choose "Choice1", while "Choice2" and "Choice3" are still visi ...

Troubleshooting: JavaScript code not functioning properly with variable input instead of fixed value

I have encountered an issue with a JS function that I'm using. The function is shown below: // A simple array where we keep track of things that are filed. filed = []; function fileIt(thing) { // Dynamically call the file method of whatever ' ...

Tips on how to display a Vue component on a new page with Vue.js router

My current challenge is getting my App to render on a new page instead of the same page. Despite trying render: h => h(App), it still renders on the same page. This is the Vue file (Risks.vue) where the router will be linked: <router-link to="/risk ...

The issue in Vue JS arises when trying to access JSON key values from an object array using v-for

I am currently working on parsing a list of objects found within a JSON payload into a table utilizing Vue.js. My goal is to extract the keys from the initial object in the array and use them as headings for the table. While the code I have in place succe ...

Dynamically update a form with steps using JQuery-steps and send all objects to the controller

In the context of a form, it is possible to dynamically add between 1 to n records before passing it to the controller with data. The following represents the ViewModel for the form: public class AddFieldDataViewModel { public int SampleID { get; se ...

how to sort arrays in javascript

When it comes to filtering items based on specific criteria like fruit and vegetable filters, what is the most effective method to retrieve items that meet both filter requirements? fruitfilter: [] = [{fruitname: "apple"} , {fruitname: "orange"}] vegeta ...

Creating an app for sending text messages and making video calls with Spring Boot technology

I am interested in developing an application with Spring Boot that allows users to make video calls and share text messages. I also want the ability to save these videos for future viewing by registered users of the app. Although I am familiar with node.j ...

Executing the serverless invoke local command produces no output

Attempting to locally run a node lambda for debugging purposes. Utilizing Serverless and the provided launch configuration in vsCode. { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launc ...

javascript making a button using an object

When trying to create a button from a JavaScript object, I am following this approach: for (buttonName in buttons){ var htmlbutton = '<button type="button" onclick="'+buttons[buttonName]()+'">'+buttonName+'< ...

What is the best way to showcase two SVG clocks on a single webpage?

The issue arises when combining the desktop and mobile versions of the clock script. The first clock works fine on its own, but upon duplicating another set of scripts for the second clock, it encounters display problems. I have appropriately labeled the c ...

Puppeteer and Chromium are ready to go with no need for any configuration

I have a specific HTTP request that I am trying to intercept, but I am encountering issues when chromium is launched through puppeteer. Some flags seem to be causing the requests to not return the expected data. However, everything works fine when I manual ...

Ways to make video controls visible following the initial click on the video

I have a collection of videos on my website and I would like them to display with a poster (thumbnail image) initially. The video controls should only appear once the user clicks on the video for the first time. Therefore, when the page is loaded, the cont ...

Can the background color of HTML header text be altered using JavaScript in JQGRID?

Can the background color of HTML header text be modified using JavaScript? Updated: Oops, I forgot to mention that it is for the header text in jqGrid. My apologies for that oversight. ...

What are the steps to integrate the aws-iot-device-sdk NPM module with Angular 11? I am encountering errors related to fs, path, and tls during the build process

I manage a browser-based Angular application that was previously on version 5.6. This app consists of two components that subscribe to an IOT topic and listen for updates without publishing. The task at hand is to upgrade to Angular 11.0.3, which I have c ...

A guide on building versatile form and input components in Vue by leveraging slots

I'm currently considering if I am following the right approach with the patterns I have implemented in my application. Is it appropriate for me to develop a reusable component called BaseForm? Another question that arises is: How can I dynamically st ...

Utilizing JavaScript to retrieve data from a self-submitting form

From my database, I am able to create a list of options for users to choose from. Once a selection is made, the values are submitted back to the same page and retrieved using Javascript. Within the same form, there are radio buttons and a multiple selecti ...

Is there a way to determine the quantity of items within a sortable div?

In my HTML document, there are multiple divs containing smaller divs that can be rearranged within each other. Upon loading the document, a random assortment of these smaller divs are added to #boxtop. Below is a snippet of my HTML code: <html> &l ...