我已申请Range(decimal, decimal,...)
到我在模型中的属性(property)。它不验证 .99
, 但验证 0.99
.
如何让前导零?
最佳答案
这是 jquery.validate.js
中数字正则表达式中的错误和 jquery.validate.min.js
默认情况下随 ASP.NET MVC 3 提供的文件。
这是来自 jquery.validate.js
的代码,第 1048 行:
// http://docs.jquery.com/Plugins/Validation/Methods/number
number: function(value, element) {
return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
}
此函数针对数字正则表达式执行字符串测试。要修复它,请将正则表达式替换为以下表达式:
/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/
.这是一个简短的版本。现在解释一下:
buggy
^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$
正则表达式读作:^-?
Beginning of line or string
-, zero or one repetitions
Match expression but don't capture it. [\d+|\d{1,3}(?:,\d{3})+]
Select from 2 alternatives
Any digit, one or more repetitions
\d{1,3}(?:,\d{3})+
Any digit, between 1 and 3 repetitions
Match expression but don't capture it. [,\d{3}], one or more repetitions
,\d{3}
,
Any digit, exactly 3 repetitions
Match expression but don't capture it. [\.\d+], zero or one repetitions
\.\d+
Literal .
Any digit, one or more repetitions
End of line or string
如您所见,第二个捕获组
(?:\.\d+)?
允许 .XX
中的数字格式,但匹配时,第一组 (?:\d+|\d{1,3}(?:,\d{3})+)
首先检查并且验证失败,因为必须匹配第一组。如果我们将引用 http://docs.jquery.com/Plugins/Validation/Methods/number演示并检查他们的正则表达式以进行数字验证,它将如下所示:
^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$
.这与 buggy one 相同,但现在第一个匹配组应该是 zero or one repetitions
或者换句话说,可选。还有这个额外的?
在正则表达式中修复错误。编辑 :这也适用于 MVC 4 默认模板。两个模板都使用 1.9.0 版本的插件。在 1.10.0 版本中,此问题已修复。来自 changelog :
所以有时保持更新是个好主意。
关于.net - 范围数据注释属性不验证 .99?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11939127/