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

Enable Google Chart to visualize multiple sets of data beyond just 2

This Google chart displays 2 data sets (Tea, Coffee). I've attempted to modify it to show 5 data sets but encountered difficulties. I experimented with changing the button.onclick function and the button value. Below you will find the original code (2 ...

Manipulating State in React: How to add a property to an object within an array within a component's state

Currently, I am retrieving an array of objects stored in the state, and I am attempting to include a new property to each of these objects. However, I am encountering a problem where even though I can see the new property being added to each object, when ...

Dealing with an empty req.body in an Express.js POST request

Having trouble solving this issue with a simple search. Can anyone provide clearer guidance? In the client-side code, I attempted to attach an object using xhr.send(obj). Currently, I'm trying to append to the formData object, but the result remains ...

Encounters a fault while processing the php output

Displaying an error in the query The browser is showing the correct answer. $.ajax({ type: "POST", url: url, async: true, contentType: " charset=utf-8", dataType: "XMLHttpRequest", success: func ...

RS256 requires that the secretOrPrivateKey is an asymmetric key

Utilizing the jsonwebtoken library to create a bearer token. Following the guidelines from the official documentation, my implementation code appears as below: var privateKey = fs.readFileSync('src\\private.key'); //returns Buffer let ...

"Caution: The `className` property did not align" when configuring a theme provider within Next.js

I'm currently working on developing a theme provider using the Context API to manage the application's theme, which is applied as a className on the body element. The implementation of the context is quite straightforward. When initializing the ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

Initiating and pausing an Interval using a single button

I'm attempting to create a JavaScript-based chronometer that starts and stops when a single button is clicked. However, I am struggling to figure out how to properly implement the setInterval function to achieve this functionality. Below is my current ...

"Exploring the dynamic features of jQuery's mobile listview and

As I work on creating a mobile app using jQuery Mobile, I find myself facing some challenges. Despite my efforts and attempts at different methods, I have not been successful in achieving the desired functionality. Specifically, I am trying to implement a ...

Creating a distinctive appearance for JavaScript's default dialogue box

Is there a way to enhance the design of my code that prompts the user for input using JavaScript's `prompt`? Currently, it appears too simplistic. Are there any CSS or alternative methods to improve its appearance? function textPrompt(){ var text = ...

JavaScript Looping through multiple files for upload will return the last file in the series

I'm currently working on implementing a multiple file upload feature using JavaScript. Within my HTML, I have the following input: <input type="file" (change)="fileChange($event,showFileNames)" multiple /> When the onChange event is triggere ...

Retrieve the specific array element from parsing JSON that includes a particular phrase

I need help filtering array values that contain the phrase 'Corp' Currently, all values are being returned, but I only want the ones with "Corp" var url = "/iaas/api/image-profiles"; System.debug("getImageProfiles url: "+url ...

The function window.addEventListener('load') functions properly on desktop computers, but does not work on mobile devices

After developing a react website, I noticed that it functions correctly on PC but not on Mobile devices. componentDidMount() { window.addEventListener('scroll', this.onScroll); // This event works fine window.addEventListener('load&a ...

Spin a child element by clicking on its parent component

I am looking to create a unique animated effect for the arrows on a button, where they rotate 180 degrees each time the button is clicked. The concept involves rotating both sides of the arrow (which are constructed using div elements) every time the con ...

Substitute link with asynchronous JavaScript and XML

I need to enable/disable user accounts by clicking on an anchor. The list of users is created dynamically using a loop. Here's an example of an anchor tag: <a href="http://www.example.com/users/deactivate/44" class="btn btn-success" title="Deactiv ...

The dominance of the parent component's scoped style over the child component's scoped style

Within my Vue application, I have two components. The main component utilizes a class named elDiv, which results in a yellow background color. On the other hand, the secondary component also employs a class named elDiv, but with a blue background color. De ...

Angular 2 keypress validation: Ensuring data integrity through real-time input verification

I am currently facing an issue with implementing number validation in my Angular2 project. I am struggling to replicate the JavaScript code provided below. Here is the HTML: <input type="text" class="textfield" value="" id="extra7" name="extra7" onkeyp ...

The use of `slot` attributes in Ionic has been deprecated and flagged by the eslint-plugin-vue

I encountered an error message while using VS Code: [vue/no-deprecated-slot-attribute] `slot` attributes are now considered deprecated. eslint-plugin-vue After installing two plugins in .eslintrc.js, I have the following configurations: 'extends&ap ...

Troubleshooting Test Failures: The importance of passing $controller in the callback of 'it' function in Angular

As a newcomer to testing, I am attempting to write Jasmine/Karma tests for a controller. Given a sample test to use as a starting point, the issue arises when passing the $controller in the argument of the it block. The test passes successfully with this s ...

Top method for transferring server (C# / Razor) data to an AngularJS application

In our use of DNN, we often encounter the need to pass specific context values (such as page id or module-on-page-id) into an AngularJS application. While we have established our own conventions for achieving this, we are interested in hearing about how ot ...