R
R
RudMa2021-10-22 09:00:57
Vue.js
RudMa, 2021-10-22 09:00:57

How to validate an input with type number Vue.js?

I don’t understand how to write a check for the entered value so that it is impossible to enter the number <1 and >99. Everything that I wrote before does not work.

<input
              class="qty__input form__input"
              type="number" 
              @input="validateInputData(product.qty)"
              v-model="product.qty">
 
<script>
 methods: {
    validateInputData(qty) {
      // this.$emit("validateInputData")
      if (qty < 1 || qty === "" || qty === 0) {
        qty = 1;
      } 
      else if (qty >= 99) {
        qty = 99;
      } 
      else {
        qty = qty;
      }
    }
</script>

How to do it correctly in vue.js?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-10-22
@0xD34F Vue.js

What is product?
If it's a single object, then it's easiest to set a watch on the property you're interested in:

watch: {
  'product.qty'(val) {
    this.product.qty = Math.max(1, Math.min(99, val | 0));
  },
},

If you have it there v-forand it's an array element, then you can deep watch the entire array:
watch: {
  products: {
    deep: true,
    handler: val => val.forEach(n => n.qty = Math.max(1, Math.min(99, n.qty | 0))),
  },
},

If you don't like watch, fix the user input directly:
methods: {
  onInput(e) {
    if (e.isTrusted) {
      e.target.value = Math.max(1, Math.min(99, e.target.value | 0));
      e.target.dispatchEvent(new Event('input'));
    }
  },
},

<input
  @input="onInput"
  ...

You can even write this as a directive:
function onInput({ isTrusted, target: t }) {
  if (isTrusted) {
    t.value = Math.max(t.min, Math.min(t.max, t.value | 0));
    t.dispatchEvent(new Event('input'));
  }
}

const minmaxDirective = {
  mounted: el => el.addEventListener('input', onInput),
  unbind: el => el.removeEventListener('input', onInput),
};

app.directive('minmax', minmaxDirective);
<input
  v-minmax
  min="1"
  max="99"
  ...

A
artloveyou, 2021-10-22
@artloveyou

<template>

<input type="number" min=1 max=5 :class="{invalid:userChoice < 1 || userChoice > 5}" v-model="userChoice" />

</template>

<script>
export default {
  data() {
    return {
      userChoice: 1
    }
  }
}
</script>

https://codesandbox.io/s/tender-dream-xxjb7?file=/...
True, it works while the selection is made with the arrows, and if you manually fill in the input, you need to cut an additional check

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question