Is there a way to transform a six-digit input into a date format using vue/JavaScript?

I've explored various solutions for this issue, but they all seem to be backend-focused. What I need is a Vue/JavaScript method. I have a string containing IDs, with the first 6 digits representing the date of birth and the final 4 digits being a personal identifier. For example, an ID will look like this: 211089-0000. So, the first 6 digits stand for DD/MM/YYYY.

I have two fields: one for entering the ID and the other for displaying the date of birth. I want the date of birth field to automatically update when an ID is entered, using the first 6 digits to convert them into a date format.

Here's how far I've progressed:

I've created a computed method like this:

updateDateOfBirth(){
    if(!this.dateOfBirth && this.userId.length > 6){
      this.dateOfBirth = this.userId.substring(0,6);
    }
  }

And I've added it as a change event in the userId input field:

<template>
  <div>
    <b-form-input v-model="userId" @change="updateDateOfBirth" placeholder="Enter your ID"></b-form-input>
    <div class="mt-2">Value: {{ userId }}</div>
  </div>

  <div>
    <b-form-datepicker id="dateOfBirth" v-model="dateOfBirth" class="mb-2"></b-form-datepicker>
    <p>Value: '{{ dateOfBirth }}'</p>
 </div>
</template>

Now, I need to convert the 5th and 6th digits into a year format, so 211089 becomes 21/10/1989. Can this be achieved using moment.js, perhaps? I haven't found any good examples yet.

Answer №1

Vue SFC Playground

I successfully implemented this using the Composition API, now it can be switched to the Options API with adjustments made to the date picker format. I utilized a standard input[type=date].

  1. Replace @change with watch as there is already a model for the ID input
  2. Use regex to extract date parts
  3. Perform validation with Date
  4. Set the error message or datepicker value accordingly:
<script setup>
import { ref, watch } from 'vue'

const userId = ref('');
const dateOfBirth = ref('');
const error = ref('');

watch(userId, userId => {
  error.value = '';
  const match = userId.match(/^(\d{2})(\d{2})(\d{2})/);
  if(match){
    let [_, d, m, y] = match;
    const curr = new Date().getFullYear().toString().slice(-2);

    y = (y > curr && y < 100 ? 1900 : 2000) + +y;
    const val = `${y}-${m}-${d}`; // customize the format
    // validate the date - convert to date and compare to the specified format
    const dt = new Date(y, m - 1, d, 0, 0, 0, 0);
    const formatted = `${dt.getFullYear()}-${dt.getMonth() + 1}-${dt.getDate()}`;
    if(formatted !== val){
      error.value = 'Invalid ID date format';
    } else {
      dateOfBirth.value = val;
    } 

  }
});

</script>


<template>
  <div>
    <input v-model="userId" placeholder="Enter your ID">
    <div style="color:red" class="error">{{error}}</div>
    <div class="mt-2">Value: {{ userId }}</div>
  </div>

  <div>
    <input type="date" id="dateOfBirth" v-model="dateOfBirth" class="mb-2">
    <p>Value: '{{ dateOfBirth }}'</p>
 </div>
</template>

Answer №2

Utilize the moment js library

<script>
import Calendar from './components/Calendar.vue';
import moment from 'moment';

export default {
  name: 'App',
  moment: moment,
  components: {
    Calendar,
  },
  computed: {
    date: function () {
      return moment('211089', 'DDMMYY').format('DD/MM/YYYY')
    }
  }
};
</script>

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

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

Issue: Spaces are not being displayed between items in the @Html.DisplayFor statement within the Foreach

I have encountered a few similar queries on this platform and attempted the suggested solutions, but unfortunately, they did not resolve my specific issue. Within my view, I am using @Html.DisplayFor in a Foreach loop to display all GroupIDs in a particul ...

Guide to establishing a connection to the Companies House API: Essential guidelines on setting up cURL headers and requisite API key specifications

I am attempting to establish a connection with the UK Companies House API, preferably using JavaScript. However, I am currently trying to set up this PHP version. How can I obtain access to the API using an API key? PHP: public function GetCompanyHouse( ...

Why is the 'Access-Control-Allow-Origin' header missing in the MEAN stack Facebook authorization error?

Currently, I am working on implementing Facebook authorization in my MEAN stack application. To achieve this, I am utilizing the passport and passport-facebook modules. It's worth mentioning that I have opted not to use jade or ejs, and instead sticki ...

How can I use JavaScript to find a keyword on a webpage that is not located within an <a> tag or its href attribute?

I'm on a mission to locate a specific keyword within a webpage. Sounds simple, right? Well, here's the tricky part - I need to disregard any instances of this keyword that are nested within an <a> tag. For example: <p>Here is some s ...

What steps can be taken to resolve an error encountered when attempting a dynamic data POST request from the body

Whenever I attempt the post method to fetch data on Postman and store it in a local MongoDB database, I encounter an error. The error message indicates a bad request with a status code of 400. *The following is app.js: var express = require('express& ...

Values returned by XmlHttpRequest

When it comes to returning data from an XmlHttpRequest, there are several options to consider. Here's a breakdown: Plain HTML: The request can format the data and return it in a user-friendly way. Advantage: Easy for the calling page to consume ...

My function doesn't seem to be cooperating with async/await

const initialState={ isLoggedIn: false, userData: null, } function App() { const [state, setState]= useState(initialState) useEffect(()=>{ async function fetchUserData(){ await initializeUserInfo({state, setState}) // encountering an ...

Obtain JSON data from an API and display it in a table using axios and Vue.js

I am working with a datatable and trying to populate it with data fetched from an API that returns JSON using the findAll() method from Sequelize. However, when I call the getUser method in console.log, it shows that the data is being retrieved. But when ...

Exploring the "else if" Statements in a JavaScript Calculator

I need help with modifying a calculator created by a former colleague at my workplace. Unfortunately, I haven't been able to contact them and I was hoping someone here could assist me. My knowledge of javascript is limited, so please bear with me if m ...

Using the html5-canvas element to drag connected lines

Here is an example of creating four points and connecting them: sample. My goal is to make it possible to drag the entire line connection when clicking on it, but when clicking on a circle, only that specific circle should be extended (already implemented ...

Most effective method to avoid updating a node_modules package

tag: After downloading and installing a node_module (npm package)... I have customized the internal files within the node_modules folder to better fit my requirements. Although using it as a node_module is most convenient for me, I am concerned that futur ...

Experience the simplicity of running basic Javascript Scratch code within IntelliJ IDEA Ultimate

Is there a straightforward way to run and debug a basic JavaScript code in IntelliJ Idea Ultimate without the need for additional setup like creating an HTML file or npm project? I'm looking to avoid boilerplate tasks and wondering if there's an ...

What is the process for implementing pagination in vue-tables-2 with a Laravel REST API?

I'm looking to implement pagination on Vue server-table using a Laravel endpoint. How can I achieve this? Below is my component setup: <template> <div> <v-server-table :columns="columns" url="/object/find" :options="option ...

Can anyone tell me how to retrieve the value of {{org}} in this situation?

<head> <title>My Unique Page</title> </head> <body> <input type="text" ng-model="selectedOrg" ng-show="!isSuperAdmin" readonly /> <select id="nameOrg" ng-model="selectedOrg" ng-cha ...

Identify when a click occurs outside specific elements

I've been searching for solutions to address this issue, but so far nothing has worked. Here is the JavaScript code I am using: var specifiedElement = document.getElementById('a'); document.addEventListener('click', function(eve ...

Navigating through HTML content and extracting specific elements

After using an ajax call to retrieve the partialView HTML of a page, I need to extract information from the main div before displaying it. This data specifically relates to the size information in order to create a floating window. Here is the code snippe ...

Encountering a 500 Internal Server Error message while attempting to access a WebMethod through ajax

I'm encountering an issue with accessing my C# WebMethod in the code behind, resulting in a 500 internal server error. I cannot figure out why it's not working, so any assistance in identifying the problem would be highly appreciated. https://i. ...

Identifying the specific npm script command that was executed

My index.js file contains scripts that can be executed like the ones below: "scripts": { "lint": "eslint .", "serve": "firebase emulators:start --only functions", "inspect": "firebase emulators:start --inspect-functions", "deploy": "fire ...

Continuously transmitting PNG files to a server. I intend to instruct the receiving browser to automatically refresh at set intervals

I have a continuous task where my code is uploading a png to an http server every few seconds. I am looking for a way to implement some kind of marker that will trigger the browser to automatically refresh every 500ms, either through browser-side javascrip ...