javascript - 在格式化数字输入时验证数字输入

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

感谢this post,我使用一个函数来用逗号格式化较大的数字,例如1,000,000 :

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

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

<input type="number" min="0" class="myclass" value="@somevalue" />

这在使用 JS 时会出现问题,因为它只需要输入数字。这让我想到了这样的问题 How to make HTML input tag only accept numerical values? ,也提供了JS解决方案。

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

最佳答案

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

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

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

在编辑文本框时,它还必须保留光标位置。我在 Updating an input's value without losing cursor position 的帮助下实现了它。 .

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, ",");
}
<input onkeyup="format(this)">

https://stackoverflow.com/questions/37640891/

相关文章:

c# - 如何格式化 MVC3 中 TextBoxFor() 显示的 DateTime?

c# - 使用语句的格式/缩进 (C#)

formatting - 取决于变量的输出格式字符串

c# - 在 Visual Studio 201x 中关闭 #region 的自动格式化

r - 将带逗号的货币转换为数字

php - 如何创建友好的日期格式(例如 "submitted 2 days ago")

sql - 需要一个工具来自动缩进和格式化 SQL Server 存储过程

java - 删除 Eclipse 中的尾随空格——来自评论

c# - 如何更改datagridview中列的颜色?

c# - 用逗号代替小数将数字格式化为字符串