Creating input fields in Vue 3: Best practices

I am looking to create an input field that automatically removes entered characters if they do not match a specific pattern.

Here is the template:

<input
  type="text"
  :value="val"
  @input="input"
/>

And here is the script:

import { ref } from "vue";
export default {
  setup() {
    let val = ref("");
    const input = ({ target }) => {
      val.value = target.value.replace(/[^\d]/g, "");
    };
    return { val, input };
  },
};

You can view the sandbox here.

Answer №1

To eliminate entered numbers, you can utilize a watcher:

const { ref, watch } = Vue
const app = Vue.createApp({
  setup() {
    let val = ref("");
    watch(val,
      (newValue, oldValue) => {
        val.value = newValue.replace(/\d+/g, "")
      },
    );
    return { val };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div>
    <input
      type="text"
      placeholder="Full Name"
      autocomplete="off"
      v-model="val"
    />
  </div>
  {{ val }}
</div>

Answer №2

To restrict user input to numbers only, HTML provides a built-in feature with the

<input type="number">
element.

Answer №3

When looking at your code, it seems that you are replacing content when a pattern is matched. However, based on your question, you want to set the content to null when the pattern is not matched.

setup() {
    let val = ref("");
    const input = ({ target }) => {
      if (target && !target.value) val.value = "";
      if (!/[^\d]/g.test(target.value)) {
        val.value = "";
      }
      val.value = target.value;
    };
    return { val, input };
  },

A more efficient approach would be to create a directive if you plan to implement this in multiple input fields.

const app = createApp({})


app.directive('text-format', {
    mounted(el, binding) {
    el._listener = el.addEventListener("input", (e) => {
      if (!binding.value.test(el.value)) {
        el.value = "";
      }
    });
  },
  unmounted(el) {
    el.removeEventListener("input", el._listener);
  },
})

Your input field should now look like this:

 <input
      v-text-format="/[^\d]/g"
      type="text"
      placeholder="Full Name"
      autocomplete="off"
      v-model="val"
    />

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

Executing a function in React JS triggered by an event

Can someone help me figure out how to properly call a function from a React component within the same class? I am working with create-react-app. SomeFunction(){ return true; } handleClick(e){ SomeFunction(); // This part doesn't w ...

What is the purpose of employing this expression in the context of requestAnimationFrame?

Can you explain the purpose of using this specific "if" statement in relation to requestAnimationFrame? if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime ...

How can you assign a default value in a React select dropdown and dynamically add the remaining values?

I'm currently developing a React application that includes a form with a select dropdown feature. My goal is to have the 'uom' field value from the selected product record automatically set as the default option in the dropdown when the user ...

Vanishing HTML upon initial entry to the site using Gatsby and Material UI exclusively in live deployment

I run a blog using Gatsby that includes Material UI components to fetch markdown files through GraphQL. During development, everything operates smoothly. However, in production (after running gatsby build && gatsby serve), the HTML doesn't di ...

Using AngularJS, we can create a nested ng-repeat with an expression to filter the

I'm having trouble using a value from the initial ng-repeat as a filter in the nested ng-repeat. The issue lies with {{alpha.value}}. It displays correctly in the first repeat, including the filter and the h3 tag. However, in the second repeat, it s ...

Retrieve information from json, divide it, and transfer it to the chart for display

Greetings everyone! In my project, I am parsing a JSON file from an online API. However, I have encountered a roadblock while trying to split the data. Despite searching extensively on platforms like YouTube, I haven't been able to find a solution tha ...

I'm just starting out with jQuery and JSON and could use some assistance with formatting the string, specifically so I can properly iterate through it

This is the controller. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> @RequestMapping("/getDropDownAjax") public void fetchData(HttpServletRequest req,HttpServletResponse resp){ System.out.println ...

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

The pug blend fails to produce the desired output

Recently, I've encountered an issue while working with Pug in a Vue.js application. The task at hand is to create a multi-level menu (with submenus) using the provided data structure: mounted () { this.catalog = [ { title: "Компр ...

Ways to remove a

After creating an npm link within a local dependency and then deleting that dependency from my hard drive, I am now attempting to remove this npm link. I have attempted the following steps: npm rm --global dependency npm uninstall dependency npm unlink - ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

Ensure that the navigation bar remains consistent when switching between pages

My issue lies within the React components I am working with. Essentially, my goal is to create a Single Page Application (SPA) using ReactJS. While setting up authentication using auth0-js, I also established some routes for navigation. The layout is stru ...

What advantages does using an RxJS Subject have over handling multiple event listeners individually in terms of speed

After investigating a page's slow performance, I identified an angular directive as the root cause. The culprit was a piece of code that registered event listeners on the window keydown event multiple times: @HostListener('window:keydown', ...

Is it possible to utilize axios in Vue while utilizing CORS in the API?

I am encountering an issue with making a GET request to a CORS enabled corona virus API using axios and Vue. I have no control over their server, and my Vue app was created with vue-cli. Interestingly, I am able to make two requests from different APIs - ...

appending a set of parameters to a website address

I am currently developing an app in a Node/Express/Jade environment. Imagine that I launch my app and navigate my browser to the following URL: /superadmin/?year=2012 Upon reaching this page, I encounter a list of objects sorted in a default order. Ther ...

proper way to delete an event listener in vue 3

I have a function that listens for viewport dimensions when the project is first mounted and also after each resize event. However, I am unsure of the correct way to remove this listener. const { createApp, onMounted, ref } = Vue; const app = createA ...

Retrieving data from an HTML input tag and storing it in a variable

I'm currently working on a project that involves reading the contents of an uploaded file through an input tag and storing it in a variable. My goal is to then use an algorithm to decrypt the .txt file: <input type="button" value="decrypt" id="dec ...

You must provide a value for a v-bind expression; an empty value was detected in "v-bind:items"

I am completely new to using Vue. I have a vue component that I am working with, where I pass some objects through the component if they are available. Here is an example of how I'm using it: <form :languages='{{ json_encode($languages) }}&apo ...

Import existing data from a pre-filled form - VueJS - Bootstrap-Vue

I'm facing an issue with a form that has linked selects. When one select is filled, the other select should also be filled with the corresponding code. However, when opening the modal with the field value, it fails to load the value. I suspect this mi ...

Attempting to initiate an AJAX request to an API

Hey everyone, I've been working on making an AJAX API call to Giphy but I keep receiving 'undefined' as a response. Can anyone offer some advice on how to troubleshoot and fix this issue? Thanks in advance for your help! var topics = ["Drak ...