1

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?

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Yes but how to you prevent users from typing in certain things? For exame the user shouldnt be able to type in, say anything other than decimal numbers.
@Asperger hey mate, check again pls, I corrected answer

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.