[Vuejs]-Write number within a range in input text

1👍

Checking min & max values for inputs can be easily achieved by tuning their HTML props. There is no need for extra validation.

<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 persist in checking every change’s values, you need to validate ranges on 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>

Here, on every change, new values are validated against min and max values, and the model gets updated.

There are some edge cases that must be addressed. Checking the min value on every input event breaks the user interface. As your min value is 100, when a number like 250 is going to be entered, at the very first step, the validation event is triggered by 2 and the value will be converted to 100. So, in practice, you cannot use the input event here. The change event must be used.

Note 1 It is a good practice to use v-model.number for numeric bindings.

Note 2 It also is a good practice to use type="number" for numeric inputs.

👤Raeisi

Leave a comment