【问题标题】:Vue.js: Only allow numbers in range with one decimalVue.js:只允许带一位小数的范围内的数字
【发布时间】:2021-07-23 20:49:42
【问题描述】:

我在尝试只允许数字时遇到问题(可能是一个点和一个小数)并且数字必须介于 0 和 10 之间。 例子:

  • 2 -> 允许
  • 8.5 -> 允许
  • 7.14 -> 不允许
  • 7.1 -> 允许
  • 10.1 -> 不允许
  • 10 -> 允许
  • 15.2 -> 不允许

首先,这是一段代码:

HTML:

<b-form-input
  v-model="userDto.score"
  @keypress="restrictScoreValue"
  type="number"
  min=0
  max=10
/>

JavaScript:

restrictScoreValue($event) {
  const keyCode = ($event.keyCode ? $event.keyCode : $event.which)

  // only allow number and one dot
  if ((keyCode < 48 || keyCode > 57) && (keyCode !== 46 || this.userDto.score.indexOf('.') !== -1)) { // 46 is dot
     $event.preventDefault()
  }

  // restrict to 1 decimal place
  if (this.userDto.score !== null && this.userDto.score.indexOf('.') > -1 && (this.userDto.score.split('.')[1].length > 0)) {
    $event.preventDefault()
  }
}

它只允许点后的数字和一位小数。但是只允许 0 到 10 之间的数字是行不通的(我可以在点前输入很多数字),如果我粘贴了不正确的分数(例如:15.43),它允许。

如何改进代码以满足需求?

【问题讨论】:

    标签: javascript vue.js validation bootstrap-vue


    【解决方案1】:

    我想出了这个解决方案。使用:formatter 解决了b-form-input 的反应性问题,因此无需删除它。我有一个可配置的validation 变量,您可以配置和调整您的验证以设置maxmindecimal 值。

    new Vue({
      el: "#app",
      data: function() {
        return {
          value: 0,
          last_value: 0,
          validation: {
            min: 0,
            max: 10,
            decimal: 10
          }
        }
      },
      methods: {
        format_number(e) {
          if (e > this.validation.max) {
            return this.validation.max
          } else if (e < this.validation.min) {
            return this.validation.min
          } else if (Math.round(e * this.validation.decimal) / this.validation.decimal != e) {
            return this.last_value
          } else {
            this.last_value = e
            return e
          }
        }
      }
    });
    <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.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
    <script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
    
    <div id="app">
      <b-form-input type="number" :step="0.1" v-model="value" :formatter="format_number" />
    </div>

    【讨论】:

    • 谢谢!这对我很有帮助。这段代码对我有用。
    • 欢迎您:)。如果您觉得有帮助,请考虑接受。 @MikeJenses
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2020-01-13
    相关资源
    最近更新 更多