如何在 MVC 中强制执行唯一字段验证
我正在构建一些 MVC 应用程序,我真的很喜欢 MVC 中的数据注释支持。内置支持足以执行简单的验证检查。我想知道如何使用自定义数据注释实现唯一字段验证?例如,我有一个视图模型,需要用户注册一个新的登录名,有没有办法在调用数据库提交之前检查(使用 Model.IsValid)该名称是否不存在?
I am in the way building some MVC Application and I really love the Data Annotations support in MVC. The build in support is good enough to enforce simple validation checkup. I wonder, how to implement unique-field validation using custom data-annotation ? For example, I have a view model that need the user to register a new login name, is there way to check (using Model.IsValid) whether the name is not existed before calling the db submit?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜您可以编写自己的验证器属性来检查数据库,或者您可以加载所有数据并进行检查。
我更倾向于简单地尝试写入数据库并在表中具有唯一约束。如果您返回一个错误,表明存在重复插入错误,那么您只需将其显示给用户即可。
我不想提前阅读并检查自己。
编辑
我想您也可以在执行插入的代码中进行检查。您可以进行读取,如果没有找到则插入。
如果您确实发现重复项,则可以添加到模型验证违规规则并将其返回,以便错误将显示在页面上的验证摘要中。
You could write your own validator attribute to check the database I guess or you could load all the data in and checkagainst that.
I'd be more inclined to simply attempt to write to the database and have the unique constraint in the table. If you get back an error indicating that there is a duplicate insert error then you simply show that to the user.
I wouldn't be looking to read ahead and check myself.
EDIT
I guess you could also do the check in the code that does the insert. You could do a read and if none is found then insert.
If you do find a duplicate, you could add to the models validation violation rules and return it so that the error would appear in the validation summary on the page.
创建您自己的属性,该属性继承自 ValidationAttribute(DataAnnotations 命名空间中所有验证属性的基础)。通过检查用户 ID 唯一性来重写 IsValid 方法。
Create your own Attribute which inherits from ValidationAttribute(the base for all the validation attributes in the DataAnnotations namespace). Override the IsValid method with a check for user id uniqueness.