Restricting number input value in Vue using TypeScript

I have a component that looks like this:

<input class="number-input py-1 primary--text font-weight-regular"
        :ref="'number-input-' + title"
        @keypress="onKeyPressed"
        :disabled="disabled"
        type="number"
        v-model="result"
        :min="minimum"
        :max="maximum"
      />
import { Component, Prop, Vue } from 'vue-property-decorator'
import { floatFixedNumber } from '@/common/utils'

@Component({
  name: 'NumberInput'
})
export default class NumberInput extends Vue {
  @Prop({ type: String }) title!: string | null
  @Prop({ type: Number }) value!: number
  @Prop({ type: Boolean, default: false }) focused!: boolean
  @Prop({ type: Number, default: 0 }) minAllowed!: number
  @Prop({ type: Number, default: 999 }) maxAllowed!: number
  @Prop({ type: Boolean, default: false }) disabled!: boolean

  get result (): number {
    return this.validateValue(this.value)
  }

  set result (value: number) {
    if (!this.disabled) {
      this.$emit('on-change', this.validateValue(value))
    }
  }

  get minimum (): number {
    return this.minAllowed === null ? 0 : this.minAllowed
  }

  get maximum (): number {
    return this.maxAllowed === null ? 999 : this.maxAllowed
  }

  onKeyPressed () {
    this.$nextTick(() => {
      this.$forceUpdate()
    })
  }

  validateValue (value: string | number | null): number {
    value = Number(value)
    value = isNaN(value) ? 0 : value
    value = value < this.minimum ? this.minimum : value > this.maximum ? this.maximum : value
    return floatFixedNumber(value)
  }

  mounted () {
    if (this.focused && this.$refs['number-input-' + this.title]) {
      (this.$refs['number-input-' + this.title] as HTMLElement).focus()
    }
  }
}

My goal is to limit the maximum allowed number to 999. However, even though I have set the max number to 999, users can still type 9999 into the input field.

I have already tried the following approaches:

get result (): number {
    const num = this.validateValue(this.value) > this.maximum ? this.maximum : this.validateValue(this.value)
    return num
  }

onKeyPressed (event:any) {
    const val = this.validateValue(event?.target.value)
    if (val > this.maximum) {
      this.result = this.maximum
    } else {
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    }
  }

And another approach:

onKeyPressed (event:any) {
    const val = this.validateValue(event?.target.value)
    if (val > this.maximum) {
      (this.$refs['number-input-' + this.title] as HTMLInputElement).value = this.maximum.toString()
    } else {
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    }
  }

Despite trying these solutions, users are still able to input 9999 in the field even though the maximum allowed number is set to 999. Is there a way to prevent this and limit input to a maximum of 999?

Answer №1

<input 
  class="number-input py-2 primary--text font-weight-regular"
  :ref="'number-input-' + title"
  @keydown="onKeyPressed($event)"
  :disabled="disabled"
  type="number"
  v-model="result"
  :min="minimum"
  :max="maximum"
/>

onKeyPressed: (e: KeyboardEvent) => {
    const input: HTMLInputElement = (e.target as HTMLInputElement) ?? null;
    if (input && input.value.length > 3) {
        e.preventDefault();
    }
};

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

Ways to showcase product information (Using Angular and Firebase)

Information product.model.ts id?: string; name: string; price: number; sale_price: number; description: string; tech_sheet: string; imageUrls: string[]; category: string; createdAt: Date; } Initialize file product.service.ts The latest f ...

Using TypeScript import statements instead of the <reference path...> in an ASP.NET Core web application: A step-by-step guide

Understanding the Setup I initially had a functional TypeScript Hello World in my ASP.NET Core Web application. To compile TypeScript, I used the NuGet package "Microsoft.TypeScript.MSBuild" Version="4.4.2" along with a tsconfig.json f ...

Can a strict type be created from a partial type?

By utilizing TypeScript 2.1, we have the ability to generate a partial type from a strict type as demonstrated below: type Partial<T> = { [P in keyof T]?: T[P]; }; type Person = { name: string, age: number } type PersonPartial = Partial<Pers ...

Incorporating a library downloaded from GitHub into a Vue project instead of relying solely on npm installation

I've been struggling to install the https://github.com/MadimetjaShika/vuetify-google-autocomplete library through npm. I am new to using vue, and I need to install the prerelease developer's build, version 2.0.0-Alpha.9, because the older one is ...

What is the best way to ensure an observable has been updated before proceeding with additional code execution?

Is an observable the best choice for providing live updates of a variable's value to another class? I have a loop in my service class that looks like this: elements.forEach(element => { doStuff(); this.numberSubject.next(valueFromDoStuff); }) ...

Unable to leverage vscode workspace path for the next js 13 project

I am facing an issue with TypeScript despite having the latest versions installed in my project (TypeScript 5.2.2 and @types/react 18.2.21): Next 13 — client and async server component combined: 'Promise<Element>' is not a valid JSX elem ...

Is it possible to integrate SVGs into Nuxt with Vue.js without the need for importation?

I am currently working with Nuxt and Vue.js, attempting to display some SVG images on the webpage. However, I keep encountering the following issue: https://i.sstatic.net/lJ3dc.png Ignore the pink color, as it comes from another element. I have tried ins ...

Importing TypeScript enums into a Vue or browser context can lead to errors or the need for additional dependencies

I'm encountering a problem when trying to import type definitions from a separate module in my Vue project. Below is the structure of the typedefs I am attempting to import: import { Server, createServer } from "net"; export namespace Testable { ...

Utilizing React Higher Order Components with TypeScript: can be initialized with a varied subtype of restriction

I am currently working on creating a Higher Order Component (HOC) that wraps a component with a required property called value, while excluding its own property called name. import React, { ComponentType } from 'react'; interface IPassThro ...

Programmatically configure filter settings for vue-good-table

Is it possible to dynamically change the displayed value in UI filter elements (such as input fields and dropdowns) within vue-good-table? For instance, if I were to execute the following code: this.$set(this.table.columnsFilters, 'name', ' ...

Sharing data between parent and child component in Vue - sending a variable as a prop

I recently started using Vue and decided to integrate a Pomodoro timer component into my app. The timer component I found on GitHub (https://github.com/P3trur0/vuemodoro) works well, but I encountered an issue where the time cannot be adjusted within the a ...

Framer Motion's "repeatType" property triggering a TypeError

Every time I try to add the repeatType property in my transition, I encounter an error related to the variants prop: index.d.ts(2779, 5): The expected type comes from property 'variants' which is declared here on type 'IntrinsicAttributes ...

Issue with Angular 2 Observable testing: Trying to use setInterval in an async zone test is not allowed

I am currently in the process of testing a component that relies on a service for making asynchronous HTTP calls. The service returns an Observable, which is then subscribed to by the component. Snippet from the service code: getRecentMachineTemperatures ...

Is there a way to verify the presence of data returned by an API?

I am trying to implement a system in my Index.vue where I need to check if my API request returns any data from the fetchData function. Once the data is fetched, I want to return either a boolean value or something else to my Index.vue. Additionally, I wou ...

What is the best way to inform the user of their login status in Angular?

As a newcomer to angularfire2, I am currently working on implementing authentication and providing the user with feedback on their login status. I am using version angularfire2": "^5.0.0-rc.4. I came across an example on this site, but I am unsure of how i ...

What is the best way for me to generate a fresh object?

In one of my components, I have implemented a feature where clicking on an image toggles a boolean variable to show or hide a menu. The HTML structure for this functionality is as follows: <img src="../../assets/image/dropdown.png" class="dropdown-imag ...

Having trouble with custom padding for b-sidebar in VueJS?

I am struggling with adding padding to the sidebar using bootstrap-vue. When I attempt to add padding in the browser devtools, it works perfectly fine. However, when trying to implement the same code, it doesn't reflect on the actual webpage. I tried ...

How can I display a spinner/loader gif when the page loads using Vue?

When it comes to loading components on a webpage, jquery has the options of $( document ).ready() and onload. But in Vue, how can we achieve the same effect? For example, when a user clicks our page, how can we display a spinner until all contents are load ...

What is the reason for not requiring checks with Union Types when utilizing a variable, yet necessitating them within a function?

Currently working on some Typescript challenges and encountered a scenario involving a union type. In this example, the function getIstanbulPostalCode is declared to return either a string or a number: function getIstanbulPostalCode(): string | number { ...

Logging into Twitch API using asynchronous functions and VueJS

Hey there, I'm currently utilizing Nuxt to develop an application that integrates with Twitch. One of my main goals is to allow users to easily sign in using their Twitch credentials. I have already set up the necessary components within Twitch and o ...