2

I'm trying to figure out the best way to validate data within a MVC C# app and xVal seemed to be the best fit. However I'm running into a problem with data type validation.

At first I was doing an UpdateModel into the DTO and then running the validation on the DTO. This worked great for things like required fields, however UpdateModel would throw an exception if you tried, for example, to map a string ("asd") into a decimal field. Since UpdateModel had to be ran before there was any data to validate I wasn't sure how to get around that.

My solution was to create a DTO per form that UpdateModel would copy into, run validation on that, and then copy values out into the proper DTOs. All the attributes on the form DTO would be strings so UpdateModel never bombs out, and I'd enforce the data validation through xVal. However while rules like required are kicking in, I can't seem to get the DataType rule to kick in (in this case trying DataType.Currency).

I had also tried getting the client-side validation to work, but I was hoping there was a clean way to do server-side validation of data types.

What have others done with regards to validating data types on the server-side?

4

2 回答 2

2

我最终做的是创建一些代表表单的 DTO。这些 DTO 将采用 Request.Form 并自动将所有表单值映射到内部属性(例如公共字符串电子邮件、公共字符串名字),基于它们与表单值的名称相同。

它们将具有所有字符串属性,我会将 xVal 属性放在它们上面。然后我会使用 xVal 和正则表达式来确保传入的数据是有效的(例如有效的日期、电子邮件、号码等)。这样就永远不会抛出异常,因为它总是进入一个字符串,而不是 .Net 试图将其解析为日期或其他内容。

这将确保数据始终发送到 xVal,我可以在其中运行我想要的验证,然后在我知道我有有效数据后将其转换为正确的类型,如 DateTime。

于 2010-01-07T19:31:20.570 回答
1

我正在使用从 ValidationAttribute 派生的自定义验证器来验证应该在服务器端从字符串解析为其他数据类型的数据。例如:

public class DateAttribute : ValidationAttribute
    {

        public override bool IsValid(object value)
        {
            var date = (string)value;
            DateTime result;
            return DateTime.TryParse(date, out result);
        }
    }

我还找到了一种无需编写任何自定义 JavaScript 代码即可将此类验证属性转换为客户端和服务器端验证属性的方法。我只需要从不同的验证属性基类派生。如果您想了解更多信息,请查看我关于客户端验证的博客文章。

于 2009-09-02T19:05:01.657 回答