Javascript百分比验证 [英] Javascript percentage validation

查看:75
本文介绍了Javascript百分比验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个正则表达式来验证0 100的百分比并允许两个小数位。

I am after a regular expression that validates a percentage from 0 100 and allows two decimal places.

有没有人知道如何做到这一点或知道在javascript中有用于客户端验证的常见正则表达式示例的好网站?

Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript?

@Tom - 感谢您的提问。理想情况下,没有前导0或其他尾随字符。

@Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters.

感谢所有回复的人。我发现这些评论非常有趣。

Thanks to all those who have replied so far. I have found the comments really interesting.

推荐答案

我只是将用户输入的数字转换为浮点值,然后检查所需的范围(0到100)。尝试使用正则表达式进行数值范围验证几乎总是错误的工具。

Rather than using regular expressions for this, I would simply convert the user's entered number to a floating point value, and then check for the range you want (0 to 100). Trying to do numeric range validation with regular expressions is almost always the wrong tool for the job.

var x = parseFloat(str);
if (isNaN(x) || x < 0 || x > 100) {
    // value is out of range
}

这篇关于Javascript百分比验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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