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

Having trouble pinpointing the element with protractor's binding locator

<div class="apiRequestDisplay ng-scope"> <pre class="ng-binding">GET</pre> <pre class="ng-binding">v1/securityprofiles/{securityProfileID} </pre> </div> I am trying to target the specific text within v1/secur ...

Jest is having trouble locating numerous files within the __tests__ directory

I'm facing an issue while trying to use jest with the vue.js framework. When running yarn test:unit (e.g. vue-cli-service test:unit), only the last file in the tests folder is being recognized, even though there are several files present. I have tried ...

Having trouble with a JavaScript Promise that seems to be stuck in limbo

I have developed two custom promises that are quite similar, with the only difference being that they operate on distinct user inputs. Both promises utilize various classes and methods from Google Maps API v-3. What's puzzling is that when the first ...

Unable to change the variable for the quiz

Currently, I am in the process of developing a quiz app and I am facing an issue with my correct variable not updating. Whenever I trigger the function correctTest() by clicking on the radio button that corresponds to the correct answer, it does get execut ...

``The presence of symlink leading to the existence of two different versions of React

Currently, I am working on a project that involves various sub custom npm modules loaded in. We usually work within these submodules, then publish them to a private npm repository and finally pull them into the main platform of the project for use. In orde ...

Ways to remove a vuejs component externally

I have constructed a Vue.js component like this: var tree_data = Vue.extend({ template: '#tree_data_template', props: [ 'groupmodal', 'search-name', 'tree-id' ], data: functio ...

How can I link two separate webpages upon submitting a form with a single click?

Here is a snippet of my code: <form action="register.php" method="post"> <input type="text" name="uname"> <input type="submit" > </form> Within the register.php file, there are codes for connecting to a database. I am looking ...

Endless cycle of socksjs in vue.js

I am currently utilizing vue.js in conjunction with a flask server. The vue.js dev environment on port 8080 forwards axios queries to port 80, where my Python flask server is constantly waiting for web service calls. Below is the content of my vue.config. ...

Validation in Ajax Response

When receiving an object from my API call, I want to perform error checking before displaying the JSON data in my view. function response(oResponse) { if (oResponse && oResponse != null && typeof oResponse === "object" && oResponse.response ...

Tips for integrating JavaScript libraries with TypeScript

I'm looking to add the 'react-keydown' module to my project, but I'm having trouble finding typings for it. Can someone guide me on how to integrate this module into my TypeScript project? ...

Iterate through the list retrieved from the backend

I have a list coming from the backend that I need to iterate through and hide a button if any element in the list does not have a status of 6. feedback The response returned can vary in length, not always just one item like this example with 7 elements. ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

A guide on extracting data from a mongoose model and assigning it to a variable in a manner similar to the MVC design pattern

Below is an example of MVC framework code in PHP. I'm seeking advice on how to implement a similar process in Node.js using Mongoose. I am working with Node.js, MongoDB, and REST API development. Controller file: <?php class Myclass { public fu ...

Conceal certain digits of a credit card number in a masked format for security purposes

Is there a reliable method to mask Credit Card numbers in password format within a text field? **** **** **** 1234 If you are aware of a definitive solution, please share it with us. ...

How can Angular be used for live search to provide precise search results even when the server does not return data in the expected sequence?

Currently, I am in the process of constructing a website for one of my clients. The search page on the site is designed to update search results as you type in the search bar - with each keystroke triggering a new search request. However, there's an i ...

Encountering a NextJS error when attempting to access a dynamic route

I am currently working on a Next.js application that involves dynamic routing. I have encountered an error message stating: Error: The provided path X0UQbRIAAA_NdlgNdoes not match the page:/discounts/[itemId]`.' I suspect that the issue may be relat ...

Transforming an array of HashMaps into a JSON object within a servlet and showcasing it on a JSP page

Looking to extract all table rows and store them in an array of hashmaps, then convert them into a JSON object to be sent to a JSP page using Ajax and jQuery. Struggling with displaying the content on the JSP page. I've written the code below but need ...

Is Ruby on Rails featured in Designmodo's Startup Framework Kit?

I'm curious if the Startup Framework Kit from Designmodo can be seamlessly incorporated into my Ruby on Rails project. While I've had success integrating their Flat-UI-Pro using a gem, I haven't come across one for the Startup Framework yet. ...

The Ajax function effortlessly receives the returned value and smoothly transitions to the error handling stage

When trying to retrieve data from an ajax request, my function needs to receive the returned data as an array of strings. During debugging, I am able to see the response, but at the same time, the error function is triggered. This is how my code looks: ...

Color of the header in the tabulator

Problem with Tabulator header color customization I've been attempting to change the header color of all columns using the following CSS code, but it doesn't seem to be working as expected. I am currently working with Vue3 + Vite + Tabulator 5.4 ...