热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

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

In an asp.net-mvc project using C#.

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

I use a function to format larger numbers with commas such as 1,000,000, thanks to this post:

由于这篇文章,我使用函数用逗号(如1,000,000)格式化更大的数字:

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

The issue is, I have the inputs locked down to accept only numbers with a min value of zero.

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


This poses a problem using the JS, as it needs only number input. Which brings me to a question like this How to make HTML input tag only accept numerical values?, which also offers a JS solution.

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

I'm wondering if anyone has developed an elegant way to format numeric input display, while validating numeric input, is there are any other options available here? It doesn't have to purely be a JS solution.

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

3 个解决方案

#1


6  

You can't use the numeric input, because, well, Javascript doesn't consider formatted number to be a number.

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

The option is to use the non-numeric input but filter out any "problematic" chars.

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

In the following example, I'm also handling the dot separator in case you need to accept fractions.

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

As the text box is being edited, it also has to preserve the cursor position. I've achieved it there with the help of 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, ",");
}

#2


5  

I have the answer of your first question.

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

You can disable all keys rather than only numbers keys.

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

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

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

}

I also created working demo on jsfiddle

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

#3


2  

The program flow:
Getting the input via an on change event and calling the other functions, showing passing the data through a Ajax POST.

程序流程:通过on change事件获取输入并调用其他函数,显示通过Ajax POST传递数据。

$('.Amount').on("change", function (e) {
    var myInput = $(e.target);
    var input = this.value;
    // Remove any non digits (including commas) to pass value to controller.
    var Amount = validateInput(input);
    // Format the string to have commas every three digits 1,000,000 for display.
    var val = numberWithCommas(Amount);
    $(myInput).val(val);

    $.ajax({
        type: 'POST',
        dataType: "json",
        url: somesUrl + '/' + somethingelse,
        data: JSON.parse('{"Amount": "' + Amount + '"}'), // Amount is a nice format here and will not throw an error.
        // TODO etc
    });
});

Remove any non numbers and give a value of zero if no numbers are inputted.

删除所有非数字,如果没有输入数字,则给出零值。

var validateInput = function (input) {
    input = input.toString().replace(/[^0-9]/g, "");
    /* Remove leading zeros. */
    input = input.replace(/^0+/, '');
    if (input == "")
        input = 0;
    return input;
}

Format the input with commas 1,000,000,000.

使用逗号1,000,000,000格式化输入。

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

So even if the user types input with commas e.g. 1,734,567 it will work and if they misplace where they put a commas e.g. 17,35,555 it will still validate.

即使用户使用逗号键入输入,例如1,734,567它会起作用,如果它们错放在他们放逗号的地方,例如它将仍然有效。

See working fiddle.

看工作小提琴。

I actually worked out a nice solution while trying to meet project deadlines and in part this was solved by this answer by nicael.

实际上,我在尝试满足项目期限的过程中找到了一个很好的解决方案,部分原因是nicael通过这个答案解决了这个问题。

This solution does not check the input as it is being typed, but after it is finished, I chose the change event, as opposed to the input event, as it calls the function once and (similar to a submit event) than validates the input in one call. Removing any commas and non digits; solving the issue of formatting with commas, by removing them for the ajax call, then reformatting it with commas for the display. There is a check to remove leading zeros.

此解决方案不会在输入时检查输入,但在完成后,我选择了更改事件,而不是输入事件,因为它调用函数一次(类似于提交事件)而不是验证输入在一个电话中。删除任何逗号和非数字;解决使用逗号格式化的问题,通过删除它们进行ajax调用,然后用逗号重新格式化以显示。有一个检查删除前导零。

If all the input is garbage I replace this value with zero to prevent an error passing to the controller with null data (just a design choice, could display a toast message instead).

如果所有输入都是垃圾,我将此值替换为零以防止错误传递给具有空数据的控制器(只是一个设计选择,可以显示一个Toast消息)。


推荐阅读
  • 本文介绍了使用AJAX的POST请求实现数据修改功能的方法。通过ajax-post技术,可以实现在输入某个id后,通过ajax技术调用post.jsp修改具有该id记录的姓名的值。文章还提到了AJAX的概念和作用,以及使用async参数和open()方法的注意事项。同时强调了不推荐使用async=false的情况,并解释了JavaScript等待服务器响应的机制。 ... [详细]
  • 从零基础到精通的前台学习路线
    随着互联网的发展,前台开发工程师成为市场上非常抢手的人才。本文介绍了从零基础到精通前台开发的学习路线,包括学习HTML、CSS、JavaScript等基础知识和常用工具的使用。通过循序渐进的学习,可以掌握前台开发的基本技能,并有能力找到一份月薪8000以上的工作。 ... [详细]
  • 本文介绍了在满足特定条件时如何在输入字段中使用默认值的方法和相应的代码。当输入字段填充100或更多的金额时,使用50作为默认值;当输入字段填充有-20或更多(负数)时,使用-10作为默认值。文章还提供了相关的JavaScript和Jquery代码,用于动态地根据条件使用默认值。 ... [详细]
  • ①页面初始化----------收到客户端的请求,产生相应页面的Page对象,通过Page_Init事件进行page对象及其控件的初始化.②加载视图状态-------ViewSta ... [详细]
  • 获取时间的函数js代码,js获取时区代码
    本文目录一览:1、js获取服务器时间(动态)2 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 原文地址:https:www.cnblogs.combaoyipSpringBoot_YML.html1.在springboot中,有两种配置文件,一种 ... [详细]
  • Windows下配置PHP5.6的方法及注意事项
    本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 本文介绍了Sencha Touch的学习使用心得,主要包括搭建项目框架的过程。作者强调了使用MVC模式的重要性,并提供了一个干净的引用示例。文章还介绍了Index.html页面的作用,以及如何通过链接样式表来改变全局风格。 ... [详细]
  • 本文介绍了ASP.NET Core MVC的入门及基础使用教程,根据微软的文档学习,建议阅读英文文档以便更好理解,微软的工具化使用方便且开发速度快。通过vs2017新建项目,可以创建一个基础的ASP.NET网站,也可以实现动态网站开发。ASP.NET MVC框架及其工具简化了开发过程,包括建立业务的数据模型和控制器等步骤。 ... [详细]
  • 本文讨论了在ASP中创建RazorFunctions.cshtml文件时出现的问题,即ASP.global_asax不存在于命名空间ASP中。文章提供了解决该问题的代码示例,并详细解释了代码中涉及的关键概念,如HttpContext、Request和RouteData等。通过阅读本文,读者可以了解如何解决该问题并理解相关的ASP概念。 ... [详细]
author-avatar
谜乱凡_134
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有