使用数据注释进行自定义验证

发布于 2024-08-15 10:32:54 字数 193 浏览 8 评论 0原文

我正在使用数据注释来检查正在输入的数据,但当涉及到更自定义的数据验证方式时,我陷入了困境。

我需要对数据库运行查询以查看其中是否存在内容,然后如果出现“自定义数据库检查错误”,例如“公司名称已存在”,则向用户报告,

我如何与数据注释?

附带的 linq 和实体框架完成了所有查询等

我使用 3.5sp1 /M

I'm using data annotations to check data that's being entered, but I'm stuck when it comes to more custom way to validate data.

I need to run queries against database to see if stuff exists there or not, and then report back to user if a "custom db-check error" appears, such as "The Companyname already exists"

How can I implement such a thing together with dataannotations?

I have all the queries done etc using linq and entity framework that comes with 3.5sp1

/M

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤独陪着我 2024-08-22 10:32:54

扩展数据注释的自定义属性

您必须编写自己的属性来根据数据存储验证对象实例。

确保您的类继承 System.ComponentModel.DataAnnotations.ValidationAttribute 类:

public class MustNotExist: ValidationAttribute
{
    ...
}

注意

当我需要验证对象在数据存储中是否唯一时,我遇到了类似的情况。但是这种验证在实体类本身上是不可能的,因为它应该只适用于正在创建的那些实体,但不适用于已经从数据存储返回实体时。

我的解决方案是有一个单独的接口、类和属性。

public interface IExternalValidator ...

class DBUniqueValidator: IExternalValidator ...

class ValidateExternallyAttribute: FilterAttribute, IActionFilter
{
    ...
    public ValidateExternallyAttribute(Type validatorType, Type entityType) ...
    ...
}

我能够将我的属性放在获取实体参数的控制器操作上。然后,过滤器操作属性检查控制器操作参数(它可以轻松访问其类型和值),并根据正确的参数(在属性定义中提供的类型)运行外部验证器,并在验证失败时填充 ModelState 错误。

[ValidateExternally(typeof(DBUniqueValidator), typeof(User))]
public ActionResult RegisterUser(User newUser)
{
    if (!this.ModelState.IsValid)
    {
        // act accordingly - probably return some error depending on model state errors
    }
    // register new user in data store
}

这样我就能够仅对那些实际需要的操作运行外部验证,并且这种技术还帮助我的控制器操作代码保持干净和简短。我所要做的就是检查是否存在任何模型状态错误。

Custom attributes that extend data annotations

You will have to write your own attributes that will do the validation of your object instance against data store.

Make sure your classes inherit System.ComponentModel.DataAnnotations.ValidationAttribute class:

public class MustNotExist: ValidationAttribute
{
    ...
}

Caution

I've run into a similar situation when I needed to validate that the object is unique within data store. But this kind of validation wasn't possible on the entity class itself, since it should only work for those entities that are being created but not when you return your entity from the data store already.

My solution was to have a separate interface, class and attribute.

public interface IExternalValidator ...

class DBUniqueValidator: IExternalValidator ...

class ValidateExternallyAttribute: FilterAttribute, IActionFilter
{
    ...
    public ValidateExternallyAttribute(Type validatorType, Type entityType) ...
    ...
}

I was able to place my attribute on controller actions that get entity parameters. Filter action attribute then checks controller action parameters (it can easily access their types and values) and runs external validator against correct parameters (provided types in attribute definition) and populates ModelState errors when validation fails.

[ValidateExternally(typeof(DBUniqueValidator), typeof(User))]
public ActionResult RegisterUser(User newUser)
{
    if (!this.ModelState.IsValid)
    {
        // act accordingly - probably return some error depending on model state errors
    }
    // register new user in data store
}

This way I was able to run external validation only on those actions that actually needed it, and this technique also helped my controller actions code to stay clean and short. All I had to do is to check if there are any model state errors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文