ASP MVC中的十进制数据条目

时间:2010-12-04 03:59:03

标签: asp.net asp.net-mvc-2 jquery-plugins

public Decimal SalePrice { get; set; }

<%= Html.TextBoxFor(Model => Model.SalePrice) %>

确保用户验证或输入正确的有效方法是什么?像这样只允许数字输入和最多两个小数点?

2 个答案:

答案 0 :(得分:7)

如下所示的正则表达式应该有效:

\A\d+(\.\d{1,2})?\Z

这匹配输入,如:

2.00
25.70
04.15
2.50
525.43
423.3
52

而且,正如Mike建议的那样,您可以在数据验证属性中使用它:

[RegularExpression(@"\A\d+(\.\d{1,2})?\Z", ErrorMessage="Please enter a numeric value with up to two decimal places.")]
public Decimal SalePrice { get; set; }

编辑:回答您的两个问题:

1)这会在提交权时验证,而不是在我们失去该字段的重点时

假设您添加的所有内容都是属性,那么在提交时会进行肯定验证。从技术上讲,一旦表单参数绑定到模型,就会进行验证。但是,要实际使用它,您需要检查控制器中的验证参数:

public ActionResult MyController(MyModel model)
{
    if (ModelState.IsValid)
    {
        // do stuff
    }
    else
    {
        // Return view with the now-invalid model
        // if you've placed error messages on the view, they will be displayed
        return View(model);
    }
}

要在服务器端进行验证,除了服务器端之外,还需要使用javascript。使用Microsoft AJAX验证的一个基本示例是Scott Gu's blog

2)你能告诉我最大入口不能超过100.00且最小入口不能低于1.00的正则表达式

你可能会以某种方式在正则表达式中执行此操作,但正则表达式并不是为模式匹配而设计的。除了regex属性之外,更好的方法是添加范围验证属性。所以现在你的财产看起来像:

[RegularExpression(@"\A\d+(\.\d{1,2})?\Z", ErrorMessage="Please enter a numeric value with up to two decimal places.")]
[Range(1.00m, 100.00m)]
public Decimal SalePrice { get; set; }

以上代码未经测试,但一般方法应该有效。

答案 1 :(得分:1)

您可以使用正则表达式字符串来验证客户端和服务器端的输入。

如果在控制器操作上放置RegularExpression属性,则可以使用正则表达式字符串指定该字段需要遵循的格式。通过使用该属性,您将获得客户端和服务器端验证(假设您使用的是MVC 2.0或更高版本)。

[RegularExpression("*YourRegexExpression*", ErrorMessage="You must provide a decimal value.")]

我希望有所帮助。

请参阅Scott Gu的博客文章,其中讨论了模型验证以获取更多信息。

http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

麦克