Asperger
Asperger

Reputation: 3222

Bootstrap Vue: allow only floating point numbers for text input

How exactly do we only allow floating points numbers with bootstrap vue form inputs?

For example: 1.0, 2.20. For usability reasons I try to avoid the number type.

<template>
    <b-form-input value="text" @update="handler"></b-form-input>
</template>

<script>
  export default {
    data() {
      return {
        text: ''
      }
    }
  }
</script>

In vanilla.js I would do a regex check inside the handler and return false if the input does not fit the desired pattern, therefore preventing the user to type in anything other than decimal numbers. What is the vue + bootstrap way to achieve this?

Upvotes: 1

Views: 670

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23500

You can try with :state and computed property and allow only numbers/dot at keypress event:

new Vue({
  el: '#demo',
  data() {
    return {
      text: ''
    }
  },
  computed: {
    handler() {
       return this.text ? this.text % 1 !== 0 && !isNaN(this.text - parseFloat(this.text)) : null
    }
  },
  methods: {
    isNumber: function(evt) {
      evt = (evt) ? evt : window.event;
      let charCode = (evt.which) ? evt.which : evt.keyCode;
      if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
        evt.preventDefault();;
      } else {
        return true;
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<script src="https://polyfill.io/v3/polyfill.min.js?features=es2015%2CIntersectionObserver" crossorigin="anonymous"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>
<div id="demo">
  <b-form-input v-model="text" :state="handler" @keypress="isNumber($event)"></b-form-input>
  <b-form-invalid-feedback id="input-live-feedback" v-if="!handler">
     we only allow floating points numbers 
  </b-form-invalid-feedback>
</div>

Upvotes: 1

Related Questions