基于bool方法的自定义MVC4验证(Custom MVC4 validation based on a bool method)

编程入门 行业动态 更新时间:2024-10-24 18:26:50
基于bool方法的自定义MVC4验证(Custom MVC4 validation based on a bool method)

我有一个验证数字的方法,我没有一个正则表达式,因为它有点复杂。

public bool IsRegistrationNumberValid(int number) { ... }

在我的表单中,我有一个文本框,我想为此列添加验证。 我如何创建一个自定义注释或钩入ModelState对象来添加错误消息?

我的POST控制器操作如下所示:

[HttpPost] public ActionResult Create(UserRegistrationViewData model) { if (ModelState.IsValid) { ... } }

我不确定我有什么选项,我可以创建一个自定义属性添加到我的模型中吗? 和/或我应该只钩入模型状态并添加错误消息,然后再检查ModelState.IsValid ?

I have a method that validates a number, I don't have a regular expression for this as it is kind of complicated to create.

public bool IsRegistrationNumberValid(int number) { ... }

On my form, I have a textbox and I want to add validation for this column. How can I create a custom annotation or hook into the ModelState object to add an error message?

My POST controller action is like:

[HttpPost] public ActionResult Create(UserRegistrationViewData model) { if (ModelState.IsValid) { ... } }

I'm not sure what options I have, can I just create a custom attribute to add to my model? And/Or should i just hook into the Model state and add the error message before I check for ModelState.IsValid?

最满意答案

有几种方法可以解决这个问题,最适合您的方法将取决于以下几点:

您的IsRegistrationNumberValid方法所在的位置以及逻辑是否被移动? 你是否验证用户输入或域的完整性(你应该同时检查,但每个验证都在不同的地方)? 个人喜好。

我看到它的方式有以下几种选择:

在您的控制器中验证操作方法。 使用IValidatableObject接口进行验证。 使用自定义的ValidationAttribute 。 在你的服务层验证。

选项1:在您的控制器中进行验证:

首先,您可以简单地验证控制器操作方法中的值并更新ModelState如下所示:

[HttpPost] public ActionResult Create(UserRegistrationViewData model) { if (ModelState.IsValid) { if (!someObject.IsRegistrationNumberValid(model.value)) { ModelState.AddModelError("PropertyName", "There is an error.."); Return View() } else { // Carry out successful action here... } } }

选项2:使用IValidatableObject接口。

第二种更IValidatableObject方法是在IValidatableObject上实现IValidatableObject接口,以便将逻辑移出控制器:

public class ViewModel : IValidatableObject { public int Value { get; set; } IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { if (!staticClass.IsRegistrationNumberValid(this.Value)) { yield return new ValidationResult("An error occured"); } }

选项3:创建一个自定义验证属性。

如前所述,您可以通过从本文中所示的 ValidationAttribute派生来创建自定义验证属性。

IvalidatableObject接口和自定义验证属性之间的选择通常取决于优先级,但是, IValidatableObject接口获胜的一种情况是验证取决于多个属性(EG检查一个日期是否在另一个之后)。

选项4:在服务层进行验证。

最后,如果您的验证依赖于数据库中的其他信息,您可能需要查看本教程中关于验证服务层的信息 。 这篇文章并不完美(服务和控制器耦合有点紧密),但是一个很好的开始,只需做一些修改,就可以将数据库验证错误(例如主键违例)传递到您的用户界面中,以非常透明和用户-友好的方式。

您最终可能会使用选项2,3和4的混合。如果可能,您并不想真正使用第一个选项,因为它会使您的控制器方法更加复杂,并使其他地方的验证逻辑重用更加困难。

我的建议如下:

如果您正在验证用户输入的完整性(EG检查日期的格式是否正确),请使用IValidatableObject接口和ValidationAttribute类的混合。 如果您正在验证域的完整性(确保没有输入重复的实体,或者定义了实体之间的关系),请在服务层中执行验证。

There are a few approaches to this and the best one for you will depend on the following:

Where your IsRegistrationNumberValid method is located and whether the the logic be moved? Are you validating the integrity of the user input or the domain (you should be checking both, but the validation for each will be in a different place)? Personal preference.

The way I see it you have the following options available:

Validate in your controllers action methods. Validate using the IValidatableObject interface. Use a custom ValidationAttribute. Validate in your service layer.

Option 1: Validate in your controller:

First of all you could simply validate the value in your controllers action method and update the ModelState like so:

[HttpPost] public ActionResult Create(UserRegistrationViewData model) { if (ModelState.IsValid) { if (!someObject.IsRegistrationNumberValid(model.value)) { ModelState.AddModelError("PropertyName", "There is an error.."); Return View() } else { // Carry out successful action here... } } }

Option 2: use the IValidatableObject interface.

A second, much cleaner way is to implement the IValidatableObject interface on your viewModel so that you can move the logic out of the controller:

public class ViewModel : IValidatableObject { public int Value { get; set; } IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { if (!staticClass.IsRegistrationNumberValid(this.Value)) { yield return new ValidationResult("An error occured"); } }

Option 3: Create a custom validation attribute.

As mentioned you could create a custom validation attribute by deriving from ValidationAttribute as shown in this article.

The choice between the IvalidatableObject interface and a custom validation attribute is usually down to preference, however, one case where the IValidatableObject interface wins is when your validation depends on multiple properties (E.G. checking if one date is after another).

Option 4: Validate in your service layer.

Finally, if your validation is dependant on other information from a database you might want to take a look at this tutorial on validating with a service layer. The article is not perfect (the service and controller are a bit too tightly coupled) but is a good start and with a few modifications you can pass database validation errors (such as primary key violations) into your user interface in a very transparent and user-friendly way.

You will probably end up using a mixture of options 2, 3, and 4. You don't really want to be using the first option if possible as it makes your controller methods more complicated and makes it more difficult to reuse validation logic elsewhere.

My advice would be the following:

If you are validating the integrity of the user input (E.G. checking a date is in the correct format) use a mixture of the IValidatableObject interface and the ValidationAttribute classes. If you are validating the integrity of the domain (ensuring no duplicate entities are entered, or that relationships between entities are defined) carry out the validation in the service layer. 

更多推荐

本文发布于:2023-07-23 00:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1225215.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   方法   bool   based   method

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!