开发者

How to enforce unique-field validation in MVC

开发者 https://www.devze.com 2022-12-25 18:29 出处:网络
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 implemen

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 na开发者_StackOverflow中文版me is not existed before calling the db submit?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号