使用RegEx的JavaScript小数位数限制 [英] JavaScript Decimal Place Restriction With RegEx

查看:59
本文介绍了使用RegEx的JavaScript小数位数限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对一个文本框进行了一些客户端验证,该文本框只允许数字最多两位小数,而没有其他输入.

I have some client-side validation against a text box, which only allows numbers up to two decimal places with no other input.

此脚本仅是输入数字值的基础,但是需要对其进行修改,以便可以使用小数点,然后最多可以保留两个小数位.

This script was a basis for entering numeric values only, however it needs to be adapted so it can take a decimal point followed by only up to two decimal places.

我已经尝试过诸如/[^\d].\d{0,2}之类的事情,但是替换调用无法正常工作,而且我也不知道该怎么做.

I've tried things such as /[^\d].\d{0,2}, but then the replacement call wouldn't work, and I've got no idea how to do it.

<script type="text/JavaScript">
  function valid(f) {
    if (!/^\d*$/.test(f.value)) {
      f.value = f.value.replace(/[^\d]/g,"");
      alert("Invalid number");
    }
  }
</script>


注意

我需要匹配一个空字符串.如果提供了空字符串并提交了表单,则该值默认为零.


Note

I need to match an empty string. If an empty string is provided and the form is submitted, the value defaults back to zero.

推荐答案

The.字符在RegEx中具有特殊含义,因此需要转义.

The . character has special meaning in RegEx so needs escaping.

/^(?:\d*\.\d{1,2}|\d+)$/

这匹配123.45、123.4、123和.2,.24,但不匹配空字符串123.,123.456

This matches 123.45, 123.4, 123 and .2, .24 but not emtpy string, 123., 123.456

这篇关于使用RegEx的JavaScript小数位数限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆