Reserve a spot for a credit card in 4-digit format with VueJS

When I enter a credit card number, I want to automatically insert a space after every 4 digits. For example: 0000 0000 0000 0000 I am currently using vue js and have come across examples using jquery, but I prefer not to use jquery.

Any help would be appreciated

<!--template -->
<div>
  <div>
    <p>Card Number</p>
    <input class="cardNumber" type="tel" name="cardNumber" placeholder="Enter your card number " maxlength="19" pattern="\d*"><i class="fas fa-credit-card"></i>
  </div>
  <div>
    <p>Expiration Date</p>
    <input type="tel" name="expiration" pattern="\d*" maxlength="7" placeholder="MM / YY">
  </div>
  <div>
    <p>CVV</p>
    <input type="tel" name="cvv" pattern="\d*" maxlength="4" placeholder="CVV">
  </div>
</div>
<!-- /template -->

Answer №1

Vue2 has a feature called filters specifically designed for this purpose.

const app = new Vue({
  el: '#app',
  data(){
    return {
      cardNumber: '' 
    } 
  },
  filters: {
    formatCardNumber(value){
      return value ? value.match(/.{1,4}/g).join(' ') : '';
    } 
  },
  methods: {
    updateValue(e){
       this.cardNumber = e.target.value.replace(/ /g,'');
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<main id="app">
  <input :value="cardNumber | formatCardNumber" @input="updateValue"/>
</main>

In Vue3, the use of computed is recommended as a replacement for filters. Filters have been removed from Vue 3.0 and are no longer supported.

Vue.createApp({
      data(){
        return {
          cardNumber: '' 
        } 
      },
      computed: {
        formatCardNumber(){
          return this.cardNumber ? this.cardNumber.match(/.{1,4}/g).join(' ') : '';
        } 
      },
      methods: {
        updateValue(e){
           this.cardNumber = e.target.value.replace(/ /g,'');
        }
      }
    }).mount('#app')
<script src="https://unpkg.com/vue@next"></script>
<main id="app">
  <input :value="formatCardNumber" @input="updateValue"/>
</main>

Answer №2

In my opinion, the most convenient way to apply a pattern to input in Vuejs is by utilizing the vue-the-mask library.

For instance, here's how you can use this approach for a bank account pattern:

...

<div>
 <label>Bank Account</label>
 <the-mask
  v-model="bankAccount"
  :mask="['###-#', '####-#', '#####-#', '######-#']"
 />
</div>

...

Answer №3

Your card input seems to be linked to a data object:

data() {
  return {
    cardNumber: ''
  }
}

Within the template using v-model, you can include an event listener for keyup:

<input v-model="cardNumber" @keyup="formatCardNumber" class="creditCardNumber" type="tel" name="creditCardNumber" placeholder="Enter your credit card number " maxlength="19" pattern="\d*"><i class="fas fa-credit-card"></i>

Create a method like this:

methods: {
  formatCardNumber() {
    let num = this.cardNumber;
    (num.length - (num.split(" ").length - 1)) % 4 === 0 ? this.cardNumber += ' ' : '';
  }
}

In this method, with each keyup event, it checks if the length of the text entered in the credit card input (excluding spaces) is divisible by 4.

Answer №4

 const application = new Vue({
       el: '#application',
         data(){
          return {
           cardNumber: '' 
           } 
          },
        filters: {
           formatCard(value){
               return value ? (value.replace(/ /g, '')).match(/.{1,4}/g).join(' ') : '';
           } 
         },
         methods: {
          isNumeric(evt) {
            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
                evt.preventDefault();
            } else {
                return true;
            }
        },
            updateInput(e){
               if (e.target.value.trim() != "") {
                   this.cardNumber = (e.target.value.replace(/ /g, '')).match(/.{1,4}/g).join(' ')
                } else {
                   this.cardNumber = ""
                }
            }
         }
         })
#application {
display: flex;
    flex-direction: column;
}
#application label{ 
height: 20px;
        font-size:15px;
        color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"> 
</script>
<main id="application">
<label>{{cardNumber}}</label>
         <input placeholder="Enter Card Number" :value="cardNumber | formatCard" @input="updateInput" @keypress="isNumeric($event)"/>
      </main>
     

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

Interactive Dropdown Menus for 3 Separate Database Tables

Having trouble creating a dependent drop-down list and would appreciate some help. The error "Undefined variable: input" keeps showing up in my code. For the initial drop-down, I have 3 fixed options. <option value="business">Business</option> ...

Senecajs responded with a result that was neither an object nor an array, displaying a Promise

Seeking guidance on incorporating promises into my Seneca modules. Firstly, there is the server.js file that exposes a route: var express = require('express'); var app = express(); var Promise = require('bluebird'); var seneca = requ ...

How can I extract the domain name using a regular expression in JavaScript?

I am struggling with creating a regular expression to extract the main domain name from a URL. The URLs I have are: http://domain.com/return/java.php?hello.asp http://www.domain.com/return/java.php?hello.asp http://blog.domain.net/return/java.php?hello.as ...

Retrieve the jquery.data() of an element stored in an HTML file using JavaScript or jQuery

I have a dilemma with storing HTML in a database for later retrieval. Imagine the HTML being a simple div, like this: <div id="mydiv">This is my div</div> To store related information about the div, I use jQuery.data() in this manner ...

Using JQuery to find the nearest element and narrowing down the search to its child elements

In my program, I have 3 forms identified by form1, form2, and form3. Each form contains its own set of dropdown lists named drop1 and drop2, along with a submit button. When the submit button is clicked in any form, it checks which option was selected from ...

Is it possible to extract the value displayed on a Typography component in Material UI and store it in a state variable?

I'm currently facing an issue with mapping a data array onto material-ui Typography elements. Here's the code snippet: { array.map((item, id)=> <Typography key={id} value={item.name} />) } While this code successfully displays the val ...

Tips for adjusting the font weight and size of the label within a Quasar Tab

I've been working on my project using Q-Tab, and I've been trying to adjust the font size and weight of the tab labels without success. I've experimented with the typography options in Quasar, but nothing seems to work. <q-tabs v-model= ...

What is the best way to invoke an HTML file using a jQuery function in a JavaScript file?

When I call an HTML file from a jQuery function using require(), I am encountering an issue where I am unable to link the CSS with the HTML file. After running the file, only plain HTML is displayed without any styling. The structure of my HTML file is as ...

Searching for the precise draggable grid line position in rulerguides.js - tips and tricks!

Currently, I am utilizing rulerguides.js in my project. I have customized it for a specific div to display rulers and grid lines. You can refer to this FIDDLE. The rulers are functioning properly, but the draggable grid lines are being calculated based on ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

Retrieve the page dimensions from a Material UI component `<DataGrid autoPageSize/>`

When utilizing <DataGrid autoPageSize/>, as outlined in the documentation, you can have a Material UI table that adjusts its page size based on the browser height. However, if you are fetching data from the server progressively, it becomes essential ...

Strategies for sending data to child components in Vue

Within my parent component, I am making an API call and receiving a response. My goal is to pass this response as a prop to a child component in Vue. Below is the snippet of the parent component and the API call: <button class="btn button col-2&quo ...

Should the utilization of vue-cli and vue-cli-service be considered an unsound practice?

As I develop an application using vue-cli, I've noticed that the webpack config is not explicitly defined in my repository. It seems to be hidden from us, although it can be adjusted if needed. The default run dev script by vue-cli also utilizes vue-c ...

React-Query: executing a function after updating query data

After updating the cache in a form, triggered by a response from the server, I utilize setQueryData. However, following this cache update, my goal is to refocus on the form input field. Here are some details: Within my React application, I employ Recoil. ...

What's the best approach: Backbone-Relational discovery or retrieval?

Although the model caching feature in Backbone-Relational is effective, loading a simple model securely requires considerable code. For example: // Attempt to locate a model in the cache this.model = MyModel.find({id:id}); if(this.model){ // Model re ...

Send the contents of a `<ul>` element to the server using AJAX for form submission

Can someone assist me in submitting a serialized <ul> list through an AJAX post form request? I need help with this process. Below is my current code snippet. HTML: <form id="update_fruit_form" method="post" action="/update_fruits" accept-charse ...

Ways to access the files attribute in an input tag in AngularJS without relying on getElementById

I am currently working on file uploads using AngularJS and I have a question regarding how to retrieve input files similar to regular JS. What I want to achieve: HTML: <input type="file" name="file" id="fileImg" accept="image/*"> JS: var file ...

Choose a HTML element <a> containing a hyperlink reference and a nested child element <li>

Does anyone know of a way in javascript/css to select the (n) <li> in my code, while also specifying that the <li> must have a parent with the current <a> tag containing a specific href link? <a href="www.link.com">CATEGORY NAME& ...

Loading state with suggestions from autocomplete feature on React

In my current project, I have a component that consists of input fields and a button. The button is set to be disabled until the correct values are entered in the input fields. Everything works as expected, but there's an issue with Chrome auto-fillin ...

Populate a dropdown list with array elements using Javascript in ReactJS

I am encountering an issue while trying to populate a dropdown with data from the 'options' array. The error message states that it cannot read property appendChild of null. Using 'document.getElementByClassName' instead of document.ge ...