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

The Selenium test functions correctly in the production environment, however it encounters issues when run

I am facing an issue with my Vue.js application while writing Selenium tests. The test passes when run against the deployed production version of the app, but fails when run against a local version. When running the app locally, it is not from a build, bu ...

How can one retrieve data from two distinct API routes within a Next.js application?

Currently, I am working with Next.js and facing a challenge in fetching data from two different API routes simultaneously. My intention is to retrieve this data within the getServerSideProps function. The first dataset that I require can be found at the e ...

jquery survey quiz

Currently, I am attempting to develop a jQuery questionnaire, but my limited knowledge in the area is proving to be quite inadequate. So far, here is what I have: Upon clicking on "Questions," a pop-up window will appear with two questions. My goal is t ...

Comparing $.fn.fancybox and $.fancybox: What sets them apart?

I'd like to understand the distinction between the two items shown above. In what ways do they differ from each other? ...

When I type in the TextBox, the CheckBox value should be deactivated if it is unchecked

Whenever I attempt to input text into the textbox associated with my checkbox, the checkbox automatically becomes unchecked. How can I prevent this from happening? <span id="TRAVEL_TYPE_1"><input id="TRAVEL_TYPE_0" type="checkbox" onclick="Update ...

Updates to object properties are not appearing in Vue component

I am facing an issue with a Vue component that has a single prop, which is an object. Despite changing a property in this object, it does not reflect the update in the Vue template. Below is a simplified version of the component: <template> <p ...

What is the duration that browsers retain downloaded assets during a single session?

Is it necessary to preload data from the server in order to have immediate access when needed? The data is stored in a file named "data.json". Initially, I considered storing data.json in an object and referencing it whenever required. However, given tha ...

unable to execute PHP code

I am attempting to execute a PHP file that will update a database. On Chrome, I am encountering this error: This is the code I have in my index.html file: <!DOCTYPE html> <html> <body> <input type="text" id="descriptioninput"> ...

Automatically save user input in form fields with the help of jQuery and AJAX technology

I'm working on a form that has various input fields, and I need the data entered by the user to be automatically stored in the database every minute. After the user submits the request, it will be processed in a struts file where database interactions ...

Ways to determine the overall cost of a shopping cart using Vuejs Vuex

Running a business requires managing various aspects, including tracking the inventory. In my store, I have an array called basketContents that contains items with their respective quantities and prices. An example of how it looks is: state: { basketConte ...

Postman successfully interacts with cookies, while VueJS encounters difficulties in doing so

Currently, I have a Flask server up and running on , along with a Vue.js frontend running on http://localhost:8080. The API has been set up and tested using Postman, with everything functioning seamlessly as expected. Upon sending a POST request to /log ...

Utilizing Vue and Django: The best method for distinguishing publicPath from static file prefix

The process of transforming my extensive Django project, which currently integrates Vue from a CDN on individual frontend pages, into a Single Page Application (SPA) using NPM has presented some challenges. The backend and frontend are now separate entitie ...

Autocomplete is failing to provide any results

I am experiencing an issue with the autocomplete script as it is not displaying any names under the input field. Below is the code snippet from my index file: <head> <html lang="en"> <meta charset="utf-8"> <meta na ...

How to use Vue v-bind to fetch an array object from a different array iteration

I am currently working on a project where I have developed a table component that is utilized across multiple pages with different configurations. Each table has its own configuration stored in a separate file, containing keys, titles, and size classes for ...

Ways to resolve the issue of Parsing error: invalid-first-character-of-tag-name.eslint (vue/no-parsing-error) in Vue

Code <div class="flex justify-center"> <vs-chip v-if="current" class="text-base w-24" :color="color"> {{ getPercentage > 0 && getPercentage < 3 ...

What is the best method for conducting comprehensive testing of all projects and libraries within NestJS (nx)?

Our NestJS project has been established with multiple libraries through Nx. We have successfully run tests on individual projects/libraries using the following command: npx nx test lib1 --coverage While this method works well, we are faced with numerous l ...

`Incorporating JavaScript for Menu Navigation on the Homepage: Challenges Ahead`

I am attempting to modify the HTML link within the Javascript on the thank you page, but my attempts to change all respective pages' HTML links to index.html/javascript:goTo(XXXX) have been unsuccessful. How can I successfully alter the link to conne ...

Operating with a multidimensional entity

I am aiming for an object structure like this: {"Red 1":53,"Blue 2":26,"Green 3":25} Based on the following example: I attempted to push data from within .each loop into the object. However, due to its multidimensional nature, I'm uncertain how to ...

Using Node.js to download files with like wget, unzip them, and convert them to JavaScript without saving to

Currently, I am working on a script for a nodejs/express server-side application using the libraries request, unzip, and xml2js. The goal of this script is to fetch a zip file from a specified URL, extract an XML file from it, and then parse that XML into ...

Why Jquery's nth-child selection and conditional formatting are failing to work

I am working with a table and need to format specific data fields based on their content. For instance, any field less than 95% should be highlighted in red. Below is the jQuery code I am using: $(function(){ $('#ConditionalTable td:nth-child(2n ...