使用 AJAX 验证各个字段 - 将逻辑放在哪里?
我有一个表单,当您在字段中输入文本并关闭 Tab 时,会触发 jQuery 事件,通过调用相关的控制器操作来验证该字段。例如,我有一个 AccountController 和一个 ValidateField 操作。当用户离开用户名字段时,它将向 /Account/ValidateField 发送请求。然后我将根据验证返回 JSON 结果。
好的,假设我想验证用户名字段。我想检查是否使用了足够的字符、用户名是否尚未使用以及所使用的字符是否被允许。其中两个很容易。但是,我需要访问数据库来检查用户名是否已存在。
我该把这个逻辑放在哪里?在服务层?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在一个绝对不发生业务逻辑复制的世界中:
名称的最小长度和检查字符的有效性听起来像域逻辑,因此应该在域中。您的 ajax 调用将调用服务层,服务层又调用域并进行验证。
检查用户名是否已用于访问持久层,因此我认为这更有可能存在于服务层中。服务层可以只在存储库中查询具有指定名称的用户,如果返回任何用户,则该用户是无效的。
在我们真正关心性能的世界中:
检查用户名唯一性可能确实需要访问服务层来访问数据库。但对于其他两个,这可以在 UI 中完成,以节省前往服务层的行程,但随后需要在域中进行复制。这是 Udi Dahan 提倡的:
命令查询职责分离
他建议 UI 验证,然后在域中复制它,但不必费心从域中提供有用的消息,因为理论上只有人可能会这样做走到这一步的将是黑客。
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.