Please input a number that falls within a specified range

I need help with two text inputs that are connected v-model to a ref object. I also have two other refs, minimum (100) and maximum(1000). My goal is to allow users to input values within the range of the minimum and maximum values provided. If the value entered falls below the minimum, it should automatically default to 100. Similarly, if the value exceeds the maximum, it should default to 1000.

<input type="text" v-model="number.one" class="one" @input="validate"/> 
<input type="text" v-model="number.two" class="two" @input="validate"/>

const min = ref(100)
const max = ref(1000)

const numbers = ref({
   one: 100,
   two: 100
}) 

const validate = () => {
    if(e.target.className === 'one'){
      if(numbers.value.one <= min.value){
         numbers.value.one = min.value
      }else if(numbers.value.one > max.value){
         numbers.value.one = max.value
      }
    }
}


After implementing this, I encountered an issue where I could no longer input any values in the input field. I suspect this is because numbers.value.one is now equal to the minimum which restricts further modification. How can I overcome this limitation and still be able to update the values?

Answer №1

To easily check the minimum and maximum values for input fields, you can simply adjust their HTML properties without the need for additional validation steps.

<template>
  <input type="number" v-model="numbers.two" :max="max"/>
  <input type="number" v-model="numbers.one" :min="min"/>
</template>

<script setup lang="js">

import { reactive, ref } from 'vue';

const min = ref(100);
const max = ref(1000);

const numbers = reactive({
  one: 100,
  two: 100,
});
</script>

However, if you insist on validating every value change, then you will need to validate the ranges during input or change events.

<template>
  <input type="text" v-model="numbers.one" class="one" @input="validateMax"/>
  <input type="text" v-model="numbers.two" class="two" @change="validateMin"/>
  <!--  <input type="text" v-model="numbers.two" class="two" @input="validateMin"/>-->
</template>

<script setup lang="js">

import { reactive, ref } from 'vue';

const min = ref(100);
const max = ref(1000);

const numbers = reactive({
  one: 100,
  two: 100,
});

function validateMax() {
  numbers.one = Math.min(Number(numbers.one), max.value);
}

function validateMin() {
  numbers.two = Math.max(Number(numbers.two) || 0, min.value);
}

</script>

In this scenario, each new value is checked against the minimum and maximum values with every change, updating the model accordingly.

There are certain edge cases that should be taken into consideration. For example, continuously checking the minimum value with each input event may disrupt the user experience. If your minimum value is set at 100 and a user tries to enter 250, the validation trigger might convert it to 100 prematurely. Therefore, employing the change event is more suitable in this situation.

Note 1: Using v-model.number for numeric bindings is considered a best practice.

Note 2: Utilizing type="number" for numerical inputs is also recommended.

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

Pinia shop: Fetching initial data upon store creation

Within my Vue application, I have implemented various Pinia stores. Most of these stores require initialization with data fetched from a server, which involves waiting for a server response. To achieve this, I am utilizing the Setup style stores. I aim to ...

In search of the mean value using PHP, jQuery, and AJAX technologies

I have successfully created a star rating system using PHP and jQuery. The issue arises when attempting to display the average rate for a specific item that I am rating; instead, the average value printed is for all items being rated. Here is my jQuery co ...

Using AJAX with Rails to add data to multiple items in a one-to-many association

In my Rails application, I have set up a one-to-many association where a Song has many Channels, and each Channel belongs to a Song. The challenge I am facing is when trying to create a new Song with 6 Channels. Below is a snippet of the form in the fronte ...

Is Webpack CLI causing issues when trying to run it on a .ts file without giving any error

I am facing an issue with my webpack.config.js file that has a default entrypoint specified. Here is the snippet of the configuration: module.exports = { entry: { main: path.resolve('./src/main.ts'), }, module: { rules: [ { ...

Choose a specific value from a drop-down menu

Looking for a solution with this piece of code: $('#Queue_QActionID').change(function () { if ($(this).val() == '501' || $(this).val() == '502' || $(this).val() == '503' || $(this).val() == '504' || $( ...

The typography text exceeds the boundaries of the Material-UI CardContent

In the React Material-UI framework, I am working with a CardContent component that looks like this: <CardContent className={classes.cardContent}> <Typography component="p" className={classes.title} variant="title"> {this.props.post.title ...

Struggling to adjust the timeout to exceed 60 seconds

I have been attempting to set a timeout for 120 seconds or more, but no matter what I try, the requests are timing out after only 60 seconds. Things I have tried include: $.ajax({ url: URL, timeout: 120000, success: function(html){ co ...

What is the best way to operate both a Django and React server concurrently?

Is it feasible to run both Django and React.js servers simultaneously? Currently, I have to individually start the Backend server using python manage.py run server and then switch to Frontend to run npm start. I am working on a Fullstack project with sepa ...

Tips on Moving a Bootstrap Modal Popup with the Arrow Keys on Your Keyboard

This example showcases the integration of Bootstrap's Default Modal Popup with jQuery UI Draggable Function. The JS fiddle link provided below contains the code snippet. $(document).ready(function() { $("#btnTest").click(function() { $(&a ...

Problem with displaying images and videos in a lightbox gallery

Currently, I am encountering an issue with the lightbox feature on my website. When trying to play a video, there seems to be a layer (div tag) blocking it, preventing me from playing or stopping the video. This problem occurs when clicking on an image fir ...

Entry module could not be located due to an unresolved 'babel-loader' error

As a newbie to the world of React, I found myself facing an issue while setting up the installation and loading all the necessary dependencies. Upon running the npm start command, I encountered the following error message: ERROR in Entry module not found: ...

Connect ng-models with checkboxes in input field

I am facing an issue with binding ng-models using ng-repeat in an input checkbox tag. Let me share my code and elaborate further. app/main.html: <div ng-repeat="feature in features"> <input type="checkbox" ng-model="features[$index].name"> ...

There appears to be an issue with the compilation of the TypeScript "import { myVar }" syntax in a Node/CommonJS/ES5 application

In my Node application, I have a configuration file that exports some settings as an object like this: // config.js export var config = { serverPort: 8080 } Within another module, I import these settings and try to access the serverPort property: // ...

Determining the optimal position of a popover based on a button click, rather than from an SVG placed within the button

I've been struggling for hours to make a button click work. The button has text and an SVG, and when clicked, it should open a popover component. The popover currently calculates its position based on the element that was clicked. It works fine when ...

Step-by-step guide on accessing the Vue instance within the script tag prior to the export default in Nuxt.js

Is there a way to access properties from a plugin registered on my Vue instance in the script tag just before export? The challenge is that using the this keyword won't work to refer to the Vue instance. What alternative method can be used to access t ...

Exploring the integration of web components within VuePress

I'm currently working on integrating Stoplight into our vuepress site. This involves implementing a web component called elements-api provided by stoplight. Here's my progress so far: APIStopLight.vue <template> <main class="a ...

Guide on producing a milky overlay using Vue js

Currently, I am utilizing Vue 3 along with Bootstrap 5 in my project. In my application, there is a button and two input fields. Upon clicking the button, I would like to display a "milky" overlay as shown in this example: https://i.sstatic.net/K21k8.png ...

Baffled by the data visualization produced by Google Chart using information from

Perhaps I'm being a bit ambitious, but I managed to create a basic Chart using GoogleCharts. The problem is that I have to input the values manually, but I want to retrieve them from the Database. I know JSON can accomplish this, but I've spent f ...

Issue encountered while presenting canvas on HTML due to Firebase information

Even though I believe I'm following the correct steps, I am facing an issue where the graph displaying real-time database values is not showing up. The first image shows my real-time database and a demostration as shown in images 2 and 3. While the da ...

Is there a way to use a single function to fill and calculate multiple input fields with PHP, Javascript, and

I've encountered an issue while trying to populate a form using Javascript/ajax/php. The problem is that my function only fills in one of the required forms and then stops, even though I have received the second response from the server. Here's ...