2

I have simple input and I only need integers, but if I use e.preventDefault() and return to stop input event, input event will be still work.

input
    v-on:input="changeFraction"
    name="denominator"
    type="text"
    v-bind:value="fraction.denominator"

data() {
    return {
      fraction: {
        numerator: '',
        denominator: '',
      },
    };
  },
methods: {
    changeFraction(e) {
      const el = e.target;


      if (!/[0-9]/g.test(el.value)) {
          e.preventDefault();
          return null;
      }
        this.fraction[el.name] = el.value;

    },
  },
2
  • Use type="number", simplest solution. Commented Mar 4, 2019 at 7:43
  • @dfsq type='number' allows you to enter numbers and numbers with a remainder. But i need only whole numbers Commented Mar 4, 2019 at 7:51

2 Answers 2

1

Just use computed for validation and null for @input event when input is not valid.

For instance:

<input type="text" v-model="fraction.numerator" @input="numeratorValid ? changeFraction : null"/>
computed: {
  numeratorValid () {
    return Number.isInteger(this.fraction.numerator)
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

How be if i have second input with another data?
Make second computed method for validating another input.
0

<template>
  <div class = "fraction">

    <input
      @change = "changeFraction"
      name = "numerator"
      type = "number"
      v-model.number = "fraction.numerator" 
      />

    <input
      @change = "changeFraction"
      name = "denominator"
      type = "number"
      v-model.number = "fraction.denominator" 
    />

  </div>
</template>

<script>
  export default {
    name: 'FractionItem',
    data() {
      return {
        fraction: {
          numerator: '',
          denominator: '',
        },
      };
    },
    methods: {
      changeFraction(e) {
        const el = e.target;
        //need add plus before value, because writting letter in input change data value to string type
        if (!/[0-9]/g.test(+this.fraction[el.name])) {
          e.preventDefault();
        }

        this.$parent.changeFractionInput({
          id: this.id,
          [el.name]: +this.fraction[el.name],
          key: el.name,
        });
      },
    },
  }; 
</script>


<style lang = "scss" scoped></style>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.