如何允许用户只写00到24之间的数字

这是我的问题:我想允许用户只写00到24之间的数字。

Js代码:

const putRealTime = () => {
    const hoursRangePattern = /^(2[0-3]|1[0-9]|[0-9])$/;

    document.querySelector(".hour-min-input").addEventListener("keypress",(e) => {
        if (e.which < 48 || e.which > 57) {
            e.preventDefault();
        }
    })

    document.querySelector(".hour-min-input").addEventListener("keypress",(e) => {
        const eKey = parseInt(e.key)
        if (hoursRangePattern.test(eKey)) {
            e.preventDefault()
        }
    })
}

Ruby代码:

            <div class="hours-container-1">
              <p class="">Your event will start at :</p>
              <div class="hours-container-2 align-items-end">
                <%= f.input :min_timeh,label: false,placeholder: "hh",input_html: { min: '0',max: '24',step: '1' },input_html: { class: 'hour-min-input',maxlength: 2 }%>
                <p class="double-point">:</p>
                <%= f.input :min_timem,placeholder:"mm",max: '59',input_html: { class: 'min-min-input',maxlength: 2 }%>
              </div>
            </div>

非常感谢您!

iCMS 回答:如何允许用户只写00到24之间的数字

您正在使用f.input,所以我假设您已经安装了gem 'simple_form'。 在simple_form中:

= f.input :min_timeh,label: false,placeolder: "hh",collection: 0..23
= f.input :min_timem,placeolder: "mm",collection: 0..59

您不需要额外的JavaScript。

此外,您可以将以下验证添加到包含两列min_timehmin_timem的模型中:

validates :min_timeh,numericality: { greater_than_or_equal_to: 0,less_than_or_equal_to: 23 }
validates :min_timem,less_than_or_equal_to: 59 }

如果您想使验证更“花哨”,请使用https://github.com/DavyJonesLocker/client_side_validations

,

在您的keypress事件上,您将需要验证输入值,以访问类似以下内容的值:

document.querySelector(".hour-min-input").addEventListener("keypress",(e) => {
  const value = Math.min(24,Math.max(0,e.target.value));
  e.target.value = value;
  const eKey = parseInt(e.key)
  if (hoursRangePattern.test(eKey)) {
    e.preventDefault()
  }
})

将这两个新行捆绑在一个以事件/最小/最大为一组参数的函数中,并将其应用于事件侦听器回调返回的两个事件。

,

在js中,您可以执行以下操作:

var regexp,x;
x = $(this).val();
regexp = /([01][0-9]|[2][0-3]):[0-5][0-9]/;
if (!regexp.test(x)) {
  return $(this).val("00:00");
}

注意:对于正则表达式模式:

  • 第一部分“ [01] [0-9]”如果第一位数字在0或1之间,则第二位数字可以在0..9之间
  • 或第二部分“ [2] [0-3]”,如果第一个数字为2,则第二个数字必须在0..3之间。
  • 第三部分[0-5] [0-9]分钟,仅允许在00-59之间
  • 如果未通过正则表达式,则我们用00:00覆盖
,

希望我的正则表达式技巧更好...

B
const input = document.querySelector(".hour-min-input")

const putRealTime = () => {

    input.addEventListener("keydown",(event) => {
        const key = event.key;
        const value = event.target.value;
        const length = value.length;
        
        if (key === "Backspace") {
          return;
        }

        if((length === 0 && !/^[0-2]$/g.test(key))
        || (length === 1 && Number(value) === 1 && !/^[0-9]$/g.test(key))
        || (length === 1 && Number(value) === 2 && !/^[0-3]$/g.test(key))
        || (length >= 2)
        ) {
          return event.preventDefault()
        }
        
    })
}

putRealTime();

本文链接:https://www.f2er.com/2296505.html

大家都在问