开发者

Validating Individual Fields with AJAX - Where to put the logic?

I have a form that, when you enter text into a field and tab off, a jQuery event is triggered to validate that field by calling the relevant controller action. For example, I have an AccountController and a ValidateField action. When the user tabs off of the Username field, it will send a request to /Account/ValidateField. I will then return a JSON result back based on the validation.

Ok, so let's say I want to validate a Username field. I want to check that enough characters were used, that the username isn't already in use, and开发者_运维知识库 that the characters used are allowed. Two of these are easy. However, I need access to the database to check if the username already exists.

Where would I put this logic? In the Service layer?


In a world where absolutely no business logic replication takes place:

The minimum length of a name and checking validity of charaters sounds like domain logic, so that should be in the domain. Your ajax call would call the service layer which would in turn call the domain and validate.

Checking the username isn't already in use accesess the persistance layer, so I think this would be more likely to live in the service layer. The service layer could just query the repository for Users with the specified name, and if any are returned, it is invalid.

In a world where we actually care about performance:

The checking of username uniqueness probably does require a trip to the service layer to access the database. But as for the other two, this could be done in the UI to save a trip to the service layer, but would then need to be replicated in the domain. This is advocated by Udi Dahan:

Command Query Responsibility Segregation

He suggests UI validation, and then replicate it in the domain, but don't bother giving a helpful message from the domain because theoretically the only people who are likey to get that far will be hackers.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜