格式化数字输入时验证数字输入

Yve*_*omb 14 javascript c# validation asp.net-mvc formatting

在使用C#的asp.net-mvc项目中.

我使用一个函数用逗号来格式化更大的数字,例如1,000,000,感谢这篇文章:

function numberWithCommas(str) {
    return str.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Run Code Online (Sandbox Code Playgroud)

问题是,我将输入锁定为仅接受最小值为零的数字.

<input type="number" min="0" class="myclass" value="@somevalue" />
Run Code Online (Sandbox Code Playgroud)

这会引起使用JS的问题,因为它只需要数字输入.这让我想到这样一个问题如何让HTML输入标签只接受数值?,它还提供了JS解决方案.

我想知道是否有人开发了一种优雅的方式来格式化数字输入显示,同时验证数字输入,这里还有其他选项吗?它不一定纯粹是JS解决方案.

nic*_*ael 6

不能使用数字输入,因为,JavaScript不会将格式化数字视为数字.

选项是使用非数字输入,但过滤掉任何"有问题"的字符.

在下面的示例中,我还处理点分隔符,以防您需要接受分数.

在编辑文本框时,还必须保留光标位置.我已经在更新输入值而不会丢失光标位置的帮助下实现了它.

function format(inp){
  var start = inp.selectionStart,  // get the selection start
      end   = inp.selectionEnd;    // and end, as per the linked post
  var s1=inp.value.split(",").length-1; //count the commas before edit
  inp.value=numberWithCommas(inp.value.replace(/,|[^\d.]/g,''));
  var s2=inp.value.split(",").length-s1-1; //count the commas after edit so as to know where to place the cursor, as the position changes, if there are new commas or some commas have been removed
  inp.setSelectionRange(start+s2, end+s2); // set the selection start and end, as per the linked post
}
function numberWithCommas(str) {
  var a=str.split('.');
  var p=/\B(?=(\d{3})+(?!\d))/g;
  if(a.length>1)
    return a[0].toString().replace(p, ",")+"."+a[1];
  else 
    return str.toString().replace(p, ",");
}
Run Code Online (Sandbox Code Playgroud)
<input onkeyup="format(this)">
Run Code Online (Sandbox Code Playgroud)


小智 5

我有你的第一个问题的答案.

您可以禁用所有键,而不是仅禁用数字键.

function isNumberKey(evt)  {
    var charCode = (evt.which) ? evt.which : event.keyCode;

    if (charCode != 43 && charCode > 31
      && (charCode < 48 || charCode > 57))
        return false;
    return true;

}
Run Code Online (Sandbox Code Playgroud)

我还在jsfiddle上创建了工作演示