本文介绍了输入为0.00时,RegularExpression验证在ModelState.IsValid失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到类似于此问题的问题

我正在使用 MVC .我在ViewModel中添加了正则表达式,以强制用户输入一个1或2个小数位的数字.我认为我的正则表达式中肯定有错误,但是同一条语句在其他地方也可以正常工作.

I'm using MVC. I have added a regular expression in my ViewModel to force the users to enter a number with 1 or 2 decimal places. I am thinking there must be an error in my Regex but the same statement is working fine elsewhere.

如果我输入0.00作为我的费率,则在我提交表单时, ModelState.IsValid返回为假.

If I put in 0.00 as my rate, when I submit my form, ModelState.IsValid returns as false.

[RegularExpression(@"^(\d+\.\d{1,2})$", ErrorMessage = "Please enter valid rate with 1 or 2 decimal places")]
public double DecimalRate { get; set; }

  • 如果我输入任何无效的输入,它的行为将与预期的一样,并显示正确的错误消息,而不是让我保存页面
  • 如果我输入有效的输入(0.00以外的数字),则可以正确保存.
  • 如果我完全删除了正则表达式,则将0.00视为有效输入,它保存正确.
  • 根据此问题中的建议,我已验证此比率导致了通过在Visual Studio中的ModelState.IsValid上设置调试并检查错误来实现错误.

    As per a suggestion in this question, I have verified that this rate is causing the error by setting a debug at ModelState.IsValid in Visual Studio and checking the errors.

    我预感这可能与 double 类型的属性有关?

    I have a hunch it might have something to do with the attribute being of type double?

    推荐答案

    之所以会发生这种情况,是因为您属性的数据类型是 double (不是 string ),所以它不会t代表一系列字符.它代表一个数值.如果您输入的是 0.00 ,则它将表示值 0 ,并且与正则表达式不匹配.我怀疑您也会对 3.00 这样的数字遇到相同的问题.

    This is happening because your property's data type is double (not string), so it doesn't represent a series of characters. It represents a numerical value. If your input is 0.00, then it will represent the value 0, and not match the regex. I suspect you will encounter the same issue for numbers like 3.00 as well.

    如果您需要用户输入采用特定格式,请将字段更改为 string ,然后在需要时使用 Convert.ToDouble()将其转换为数字.

    If you need the user's inputs to be in a specific format, change your field to a string and then use Convert.ToDouble() when and if you need to convert it to a number.

    这篇关于输入为0.00时,RegularExpression验证在ModelState.IsValid失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:24