Prevent typing on input fields for numbers exceeding 3 digits

How can I prevent users from entering a number with more than 3 digits? For example, allowing entries like 150 but not accepting numbers like 1601. The keypress should be disabled in such cases.

The keypress event must be disabled.

<template>
  <b-form-input type="number" v-model="number" @input="validateNumberInput(number)">
  </b-form-input>
</template>

<script>
  export default {
    data() {
      return {
        number: "",
      };
    },
    validateNumberInput(input) {
      if (input.length >= 3) {
        input.preventDefault();
      }
    },
  };
</script>

The current code is throwing an error:

 v-on handler: "TypeError: input.preventDefault is not a function"

Answer №1

Instead of restricting users from entering invalid data, the key is to inform them why it's invalid when it occurs. The fundamental idea behind this approach is to treat users with utmost respect by not limiting their actions through restrictions like disallowing typing.

In your case, you can use the max attribute to handle validation:

<b-form-input
  type="number"
  v-model="number"
  max="999"
  @input="getPeople(number)" />

If you need more customized control over the validation message display and triggering validation events, consider using a validation plugin as outlined in BootstrapVue's documentation.

Note that adjusting the markup to comply with the preferred validation plugin's specifications will be necessary.


If you or your client insist on calling preventDefault() on the input event, check out the information provided in BV documentation:

You can access the native input and change events using the .native modifier.

To achieve this, apply the .native modifier to get the native event as a parameter. Otherwise, only the value will be obtained.

<b-form-input
  type="number"
  v-model="number"
  @input.native="getPeople" />

Then update the getPeople method:

methods: {
  getPeople(event) {
    if (event.target.value >= 1e3) {
      event.preventDefault();
      this.number = 999;
    }
  }
}

See an example in action:

let memory = 0;

new Vue({
  el: '#app',
  data: () => ({
    number: 0
  }),
  methods: {
    getPeople(event) {
      if (event.target.value >= 1e3) {
        event.preventDefault();
        this.number = memory;
      } else {
        memory = event.target.value;
      }
    }
  }
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<script src="//polyfill.io/v3/polyfill.min.js?features=es2015%2CIntersectionObserver"></script>
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<div id="app" class="m-5">
  <b-form-input type="number" v-model="number" @input.native="getPeople" />
</div>

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

Inject a dynamic URL parameter into an iframe without the need for server-side scripting

I'm really stuck and could use some assistance with the following issue, as I am unable to solve it on my own :( When a user is redirected to a form (provided via an iframe), there is a dynamic URL involved: website.com/form?id=123 The code resp ...

Struggling with implementing Bootstrap modal JavaScript in Rails 4, nothing seems to work!

This situation has been addressed in numerous posts, but despite my efforts to find a solution among them, I have yet to come across one that works for me. I am faced with the task of opening a modal that requires JavaScript modifications before being dis ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

AngularJS withCredentials Issue causing data not to be transmitted

When using AngularJS, I encountered an issue where the cookie/session was not being shared across domains for my Restful API in a subdomain. To address this problem in Angular, I added the following configuration: app.config(['$httpProvider', fu ...

How can I retrieve x-data from an external file using Alpine.js?

I recently started exploring Alpine.js and grasped the fundamentals, but I'm facing challenges when trying to move functions outside of inline script tags. Consider this snippet from index.html: <div x-data="{ loading: false }"/> &l ...

New feature alert! Introducing the Mentio JS menu now available at the bottom of the webpage

I am currently working on creating a Twitter-style @mention feature using Angular JS and a library called MentioJS. One issue I encountered is that after dynamically adding content to the page, a mysterious menu appears at the bottom of the page. This pro ...

Tips for locating a key within an object that houses a specific value in its array

In my Coffeescript code, I have created the following Javascript object: urlSets = a: [ 'url-a.com' 'url-b.com' 'url-c.com' ] b: [ 'url-d.com' 'url-e.com' 'url-f.com&a ...

What are the steps to position this bootstrap drop-down menu above a fixed page header?

Could someone please advise on what changes need to be made in the code snippet below from http://jsfiddle.net/ufkkdbja/? I am looking to ensure that when the hamburger menu is clicked, the entire menu appears without being cut off by the fixed page header ...

Retrieving User Keypad Input with Twilio Phone Calling in a Node.js Application (excluding web server)

const userInput = message.content.split(' ') const phoneNumber = userInput[1] const messageToSay = userInput.slice(2).join(' ') if (phoneNumber) { // Dial phoneNumber and deliver messageToSay, then gather ke ...

In JavaScript/jQuery, there is a technique for retrieving the values of dynamically generated td attributes and the id tags of elements inside them within tr

I am currently working on creating a calendar of events using PHP, jQuery, and ajax. The calendar is embedded within an HTML table, where the rows and fields are dynamically generated based on the number of days in a specific month. In order to successfull ...

Methods for invoking a function from a separate .js file within React Native Expo

I'm new to using React and I've come across a challenge: In my Main.js file, there is a button: import * as React from 'react'; import { StyleSheet, Text, View, SafeAreaView, Pressable, Alert } from 'react-native'; import { M ...

Swapping a value within an array and moving it to a new position

Consider this scenario: I am dealing with a list of arrays containing values like: let data = [ "10-45-23:45", "10-45-22:45", "10-45-20:45", "10-45-23:45", "10-45-23:59,00:00-04:59", "10-45-23:59, 0 ...

Transforming a radio button into a checkbox while successfully saving data to a database (toggling between checked and unchecked)

I have limited experience in web development, but I recently created a webpage that allows users to input data into an SQL database. While my code is functional, I believe there's room for optimization. I pieced it together from various online resourc ...

Create the key's value in a dynamic manner within localforage

When utilizing localForage to store data offline, I encountered an issue with generating unique key values for each form submission. My goal is to have the key value generated dynamically as 'activity_1', 'activity_2', 'activity_3& ...

Implementing multiple filters with jQuery

Make a Selection `<select class="form-control" id="technology"> <option name="sort" value="2g" id="2g"gt;2G</option> <option name="sort" value="3g" id="3g"&g ...

Is it possible to convert an NPM project into a JavaScript file that is compatible with

Can a modestly sized NPM package be transformed into a JavaScript file for direct reference in HTML using a <script> tag? The NPM package in question is straightforward and serves as an API wrapper that I wish to implement without depending on Node. ...

Node.js: The object in req is not functioning as expected

// Function to merge objects with unsent columns kept from old objects. function merge_options(obj1, obj2) { const obj3 = {}; for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; } for (var attrname in obj2) { obj3[attrname] = obj2[attrname] ...

resolve problems with Jquery scripts

Having some issues with importing a script from another file in jQuery. I have tried using $.getScript and $.ajax(); how can I incorporate a script like require.js in jQuery? util.js function getSessionInformation () { $.ajax({ url: '../contr ...

Struggling to get the hang of CSS animation?

Here is a code snippet that I am using: //Code for animating skills on view document.addEventListener("DOMContentLoaded", function(event) { function callback(observations, observer) { observations.forEach(observation => { if (observati ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...