Creating a Vue.js vuetify input that restricts the user to entering only three digits before the decimal point and two digits after the decimal point

I am looking to implement a restriction on the total number of input digits to 3. Users should be able to enter numbers like 333, 123, etc. However, if they include a decimal point, they should only be allowed to enter 2 digits after the decimal point. Valid inputs include:

123

123.33

Below is the code snippet I have developed so far:

isNumber (event, message) {
  // handling multiple decimal points
  if (!/\d/.test(event.key) && (event.key !== '.' || /\./.test(message))) {
    return event.preventDefault()
  }

  // enforcing limit of three digits before and two digits after the decimal point
  if (/^(\d{0,3}\.)?\d{1,2}$/.test(message)) return event.preventDefault()
 
}

However, the regex pattern, /^(\d{0,3}\.)?\d{1,2}$/, is not producing the desired results in my scenario.

View CodePen Demo

Answer №1

If you're looking to restrict the number of digits in an input field, one option is to use a number input (

<input type="number">
) with a max property. You can also add a small keyup handler to manage the value as needed.

document.addEventListener('keyup', handle);

function handle(evt) {
  if (evt.target.id === `num`) {
    if (evt.key === `Backspace`) { return true; }
    const [number, int] = [parseFloat(evt.target.value), parseInt(evt.target.value)];
    evt.target.value = number > evt.target.max 
      ? evt.target.max : number === int 
        ? int : number.toFixed(2);
    document.querySelector(`#value`).textContent = `current value: ${evt.target.value}`;
  }
}
<input id="num" type="number" step="0.1" max="999.99">
<div id="value"></div>

Answer №2

Here is a regex that you can utilize:

^\d{0,3}(?:\.\d{1,2})?$

Ensure to keep in mind that the decimal part, with the ., can be optional.

Check out the demo here

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 appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

The function 'downloadFunc' is not recognized as a valid function within the context of ReactJS custom hooks

Here is a unique custom hook that triggers when the user presses a button, calling an endpoint to download files as a .zip: import { useQuery } from 'react-query'; import { basePath } from '../../config/basePath'; async function downlo ...

Express.js continues to retrieve outdated query results that have already been removed from the database

I am experiencing a strange issue with my PostgreSQL and Express.js setup. Despite updating my database with new entries and deleting old ones, it seems to only display the old data that was deleted days ago. It's almost as if it's stuck in some ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

Tips for integrating Tornado authentication with AngularJS

I have been experimenting with the authentication system outlined in the tornado documentation, and I am encountering a Cross-Origin Request issue when trying to integrate it with AngularJS. Is there a way to successfully combine Tornado's authentica ...

When an AJAX call is made during a PHP session that has timed out

I am working on an AJAX form that handles data authentication. In the event of a session timeout, I need to implement a redirect to the login page. How can I go about achieving this? Here is an excerpt from my simplified server-side code: function doExecu ...

implementing dynamic binding of image src paths to backend data in a vue js application

Is there a way to bind the image src path to backend data in Vue.js? I'm familiar with how to do it on the frontend using: <img :src="require(`@/assets/${item.image}`) But how can I achieve this with backend data? ...

Problem with React Router: Uncaught Error - Invariant Violation: The element type is not valid, a string is expected for built-in components

I am encountering an issue with react-router and unable to render my app due to this error. Here is a screenshot of the error I have searched extensively for a solution but have not been able to find anything useful. Any help would be greatly appreciated ...

Encountering a mistake due to the anticipated atom not being found at the specified

In my react application, I am encountering an issue with allowing foreign characters along with English in the input field of a form. I have implemented a regular expression as follows: const alphabetRegex = /^([A-Za-z]+ )+[A-Za-z]+$|^[A-Za-z]*\p{L}/g ...

What could be the reason for my code generating the error [$http:badreq]?

I'm currently attempting to retrieve JSON data from a certain URL and am having trouble getting it to work. Despite going through the Angular documentation and other resources, I still can't pinpoint the issue due to my limited experience with An ...

Ways to identify when an HTMLElement's size changes due to a percentage-based width setting

Currently, I am in the process of developing an Angular Component and have implemented the following CSS code: :host { display: block; width: 100%; } The main objective here is to ensure that the component remains as responsive as possible. However, ...

How to Collapse or Expand Grouped Items in Vuetify 2 Data Tables

Currently, in my table, I have multiple items grouped by a string property and all groups are expanded by default. If you would like more information on the tables I am using, please visit https://vuetifyjs.com/en/components/data-tables/#grouped-rows Is ...

Navigate through the list of options by scrolling and selecting each one until the desired element is

Hey, I've got this AngularJs directive that selects an item based on the "key-pressed" event, and it's working perfectly. The issue arises when there is a scroll bar since the elements get hidden, making it difficult for me to see them. You can ...

Exploring the Usage of sessionStorage within the <template> Tag in Vue.js

Is it possible to access sessionStorage in the script section of a Vuejs component like this? <template> {sessionStorage} </template> Whenever I try to call it this way, I consistently receive the error message "cannot read property &apo ...

Having trouble getting Vue to properly focus on an input field

I am attempting to use this.$refs.cInput.focus() (cInput being a ref) but it seems to not be functioning as expected. I expect that when I press the 'g' key, the input field should appear and the cursor should immediately focus on it, allowing me ...

What is the best way to integrate Emotion styled components with TypeScript in a React project?

Currently, I am delving into TypeScript and attempting to convert a small project that utilizes Emotion to TypeScript. I have hit a roadblock at this juncture. The code snippet below export const Title = styled.div(props => ({ fontSize: "20px", ...

Ensuring precise accuracy in JavaScript; transforming 0.5 into 0.5000

My current challenge involves converting every fraction number to n decimal places in JavaScript/Node.js. However, I've encountered a roadblock as it appears impossible to convert 0.5 to 0.5000. This discrepancy is causing my test cases that anticipat ...

Tips for utilizing a unique JavaScript function with Mongoose's findByIdAndUpdate by incorporating $set:

Is it possible to update a database document using a custom JavaScript function? I am aware of the traditional method where you find -> update the document with JavaScript -> save, but this can lead to issues with concurrent data updates. Below is an examp ...

The local variable within the Angular constructor is not initialized until the ngOnInit() function is invoked

I am encountering difficulties with making backend calls from Angular. In my component, I am fetching the "category" parameter from the URL as shown below: export class ProductsComponent{ productList = [] category = "" $params; $products ...

Exploring the existence of properties using nuxt js

Hello there, I'm currently checking for the existence of {{data.name}}. If it doesn't exist, simply do not display it. Here are some iterations: <div v-if="conts.Titre || conts.keys(conts.Titre).length > 0" class="communes-contenu"> & ...