首页 > 解决方案 > 如何使用 jQuery 在 HTML 输入框中只允许数字空间和分数(1 1/2)格式?

问题描述

我正在创建一个网页,其中有一个输入文本,我希望在其中只允许数字空间和分数,例如 (1 1/2, 2 1/4, 4 1/2...)

通常 1 1/2 我们称之为 ONE AND HALF。

如何使用 jQuery 做到这一点

这是我在JSFiddle中的代码,但它没有按预期工作。

<input id="intTextBox">
(function($) {
   $.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
  if (inputFilter(this.value)) {
    this.oldValue = this.value;
    this.oldSelectionStart = this.selectionStart;
    this.oldSelectionEnd = this.selectionEnd;
  } else if (this.hasOwnProperty("oldValue")) {
    this.value = this.oldValue;
    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
  } else {
    this.value = "";
  }
});
 };
 }(jQuery));

 // Install input filters.
 $("#intTextBox").inputFilter(function(value) {
  return /^(?:(?:\d+\s)*\d+\/\d+|\d+)$/.test(value); 
  });

标签: htmljqueryvalidationnumericfractions

解决方案


您的正则表达式应包含 2 个部分:只有数字和带有可选数字部分的分数:

function test(input) {
  let pattern = /^(?:(?:\d+\s)*\d+\/\d+|\d+)$/;

  console.log(input, pattern.test(input))
}

test('1');
test('43534');
test('12/234');
test('1/2');
test('23 1/2');
test('1 1/2');
test('1.2');
test('a/b');


推荐阅读