地址字段的自定义 ASP.NET MVC 验证摘要

发布于 2024-08-12 17:54:03 字数 1140 浏览 9 评论 0原文

我正在尝试找出验证一页结账的最佳方法。 它包含:

  • 发货地址、
  • 账单地址
  • 等。Address

类显然包含 First NameLast NameStreet1Street2 >、城市邮政编码电话等。

假设用户在输入任何内容之前单击“确定” - 然后你最终会遇到十几个或更多的验证错误,给你一大块看起来很难看的红色文本。

我想将地址验证为单个实体,并给出智能错误 - 例如“不完整的地址”,或者在适当的时候给出更具体的错误。但我仍然希望能够突出显示存在问题的每个单独领域。我现在看不到执行此操作的简单方法,因为显然 Html.ValidationSummary 帮助程序将显示每个字段。

所以我想将摘要显示为:

 "Your shipping address is incomplete"

并以红色 ZipCity 突出显示。

我想我必须做一个完全自定义的 ValidationSummary,甚至可能是一个完全自定义的数据结构。

是否有任何验证框架可以使这样的摘要更容易进行,其中摘要应该显示智能摘要,而不仅仅是每个单独的字段错误。


编辑:MVC 2 RC 现在支持模型级错误。

ValidationSummary 现在支持 仅模型级别的重载 显示错误。这很有用 如果您正在显示验证 每个表单旁边内嵌的消息 场地。此前,这些消息 将在验证中重复 概括。有了这些新的变化,您 可以让摘要显示 整体验证消息(例如“有 您的表单提交有误”) 以及验证列表 不适用于的消息 特定领域。

有人有如何做到这一点的实际示例吗?

I'm trying to figure out the best way to validate a one page checkout.
It contains :

  • ship address
  • billing address
  • etc.

the Address class obvious contains First Name, Last Name, Street1, Street2, City, State, Zip, Phone etc.

Lets say the user clicks 'OK' before entering anything - then you end up with a dozen or more validation errors giving you a large block of red text that just looks ugly.

I'd like to validate the address as a single entity, and give an intelligent error - such as 'incomplete address', or more specific errors when appropriate. But I still want to be able to highlight each individual field that has a problem. I can't see an easy way to do this right now, because obviously the Html.ValidationSummary helper will show every field.

So I want to show the summary as:

 "Your shipping address is incomplete"

and highlight in red Zip and City.

I think I'd have to do a completely custom ValidationSummary, and maybe even a completely custom datastructure.

Do any validation frameworks make such a summary easier to do, where the summary should show an intelligent summary and not just every individual field error.


Edit: MVC 2 RC now supports model-level errors.

ValidationSummary now supports
overloads where only model-level
errors are displayed. This is useful
if you are displaying validation
messages inline next to each form
field. Previously, these messages
would be duplicated in the validation
summary. With these new changes, you
can have the summary display an
overall validation message (ex. “There
were errors in your form submission”)
as well as a list of validation
messages which don’t apply to a
specific field.

Anybody got an actual sample of how to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

定格我的天空 2024-08-19 17:54:03

您可以使用复合地址属性并将整个地址作为一个单元进行验证:

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string Zip { get; set; }
}

public class Order
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [AddressRequired("Your shipping address is incomplete")]
    public Address ShipTo { get; set; }

    [AddressRequired("Your billing address is incomplete")]
    public Address BillTo { get; set; }

    // you could do this if you still need 1:1 mapping for model binding
    public string ShippingCity
    {
        get { return ShipTo.City; }
        set { ShipTo.City = value; }
    }
}

验证属性将如下所示:

public class AddressRequiredAttribute : ValidationAttribute
{
    ...

    public override bool IsValid(object value)
    {
        var address = value as Address;

        if (address != null)
        {
            ...
        }
    }
}

You could go with a composite Address property and validate the whole address as a unit:

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string Zip { get; set; }
}

public class Order
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [AddressRequired("Your shipping address is incomplete")]
    public Address ShipTo { get; set; }

    [AddressRequired("Your billing address is incomplete")]
    public Address BillTo { get; set; }

    // you could do this if you still need 1:1 mapping for model binding
    public string ShippingCity
    {
        get { return ShipTo.City; }
        set { ShipTo.City = value; }
    }
}

And the validation attribute would look something like this:

public class AddressRequiredAttribute : ValidationAttribute
{
    ...

    public override bool IsValid(object value)
    {
        var address = value as Address;

        if (address != null)
        {
            ...
        }
    }
}
匿名的好友 2024-08-19 17:54:03

IDataErrorInfo 有两个成员:

  • Error - 获取一条错误消息,指示此对象出了什么问题。
  • Item - 获取具有给定名称的属性的错误消息。

如果您实现 Error 成员,您将收到一条错误消息。

IDataErrorInfo has two members:

  • Error - Gets an error message indicating what is wrong with this object.
  • Item - Gets the error message for the property with the given name.

If you implement Error member, you'll have one error message.

最笨的告白 2024-08-19 17:54:03

我在最近的项目中处理了类似的问题,我做了一个自定义的验证摘要,这里是代码:

<%
      if (!ViewData.ModelState.IsValid)
       {
           Response.Write("<div class=\"prepend-1 span-10 last notice\">");
           Response.Write("<span>Please fix fields marked with an asteristk <span class=\"ss_sprite ss_asterisk_orange\"> </span></span>");
           Response.Write("<ul>");
           foreach (KeyValuePair<string, ModelState> keyValuePair in ViewData.ModelState)
           {
               foreach (ModelError modelError in keyValuePair.Value.Errors)
               {
                %>
                <li><%= Html.Encode(modelError.ErrorMessage)%></li>
                <%
       }
           } Response.Write("</ul>");
           Response.Write("</div>");
       }
    %> 

我在部分视图中完成了它,但也许最好将其包装在 HTML Helper 方法中,就像原始的 ValidationSummary 一样。

您可以在里面检查是否有任何特殊和独特的要求。
希望有帮助。

I deal with a similar problem in a recent project, i did a custom Validation Summary, here is the code:

<%
      if (!ViewData.ModelState.IsValid)
       {
           Response.Write("<div class=\"prepend-1 span-10 last notice\">");
           Response.Write("<span>Please fix fields marked with an asteristk <span class=\"ss_sprite ss_asterisk_orange\"> </span></span>");
           Response.Write("<ul>");
           foreach (KeyValuePair<string, ModelState> keyValuePair in ViewData.ModelState)
           {
               foreach (ModelError modelError in keyValuePair.Value.Errors)
               {
                %>
                <li><%= Html.Encode(modelError.ErrorMessage)%></li>
                <%
       }
           } Response.Write("</ul>");
           Response.Write("</div>");
       }
    %> 

I did it in a Partial View, but maybe is better wrap this in a HTML Helper method, just like the original ValidationSummary.

Inside you can check for any special and unique requirements.
Hope it Helps.

后来的我们 2024-08-19 17:54:03

我会这样做:

将验证错误放入 ModelState 中,无论哪种方式对您来说都是最舒服的。您可以使用 IDataErrorInfo 或使用 DataAnnotations 和验证运行器将它们直接添加到控制器中的 ModelState。只要您用错误填充 ModelState 并重新显示视图,这并不重要。

然后,确保您的所有输入也有一个相应的 Html.ValidationMessage() 与您的表单中的它们关联:

<%= Html.TextBox("city") %>
<%= Html.ValidationMessage("city", "*") %>

根据验证错误类的 css 规则,这会将文本框变成红色,并在其旁边显示一个红色星号,告诉您他们需要纠正他们的输入的用户。

最后,由于您对显示完整的验证摘要不感兴趣,因此只需执行一个简单的检查以查看 ModelState 是否有效,如果不有效,则显示您的通用消息。

<% if (!ViewData.ModelState.IsValid) { %>
    <div id="validation-message">Your Shipping Address in Incomplete</div>
<% } %>

该解决方案将突出显示用户错误填写的特定字段,并显示您想要的错误的简短描述。

Here is what I would do:

Put your validation errors into ModelState whichever way is the most comfortable to you. You can add them directly to ModelState in your controller, using IDataErrorInfo, or with DataAnnotations and a validation runner. It doesn't really matter as long as you populate ModelState with your errors and re-display the view.

Then, make sure all your inputs also have a corresponding Html.ValidationMessage() associated with them in your form:

<%= Html.TextBox("city") %>
<%= Html.ValidationMessage("city", "*") %>

Depending on your css rules for the validation error classes this will turn the text-box red and display a red asterisk next to it telling the user they need to correct their input.

Finally, since you're not interesting in displaying the full validation summary just do a simple check to see if ModelState is valid, and if not display your generic message.

<% if (!ViewData.ModelState.IsValid) { %>
    <div id="validation-message">Your Shipping Address in Incomplete</div>
<% } %>

This solution will highlight the specific fields that the user has incorrectly filled out and display a short description of the errors like you want.

枕头说它不想醒 2024-08-19 17:54:03

Scottgu 刚刚发布了 关于新验证功能的精彩博客文章

虽然它没有深入探讨如何实现模型级验证,但它指向默认的 ASP.NET MVC 2 应用程序项目模板作为如何执行此操作的说明:

除了创建验证之外
适用于个人的属性
对象上的属性,您还可以
应用验证属性
班级级别
– 这使您可以
执行验证逻辑
一个对象内的多个属性。
作为一个实际的例子,您
可以审查
“PropertiesMustMatchAttribute”自定义
属性包含在
AccountModels.cs/vb 文件内
默认 ASP.NET MVC 2 应用程序
项目模板(只需执行文件->新建
VS 中的 ASP.NET MVC 2 Web 项目
2010 年并寻找此类)。

Scottgu just released a great blog post on the new validation features.

While it doesn't go into depth on how to implement model-level validation it points to the default ASP.NET MVC 2 application project template as an explanation of how to do this:

In addition to creating validation
attributes that apply to individual
properties on an object, you can also
apply validation attributes at the
class level
– which allows you to
perform validation logic across
multiple properties within an object.
For an example of this in action, you
can review the
“PropertiesMustMatchAttribute” custom
attribute that is included in the
AccountModels.cs/vb file within the
default ASP.NET MVC 2 application
project template (just do a File->New
ASP.NET MVC 2 Web Project within VS
2010 and look for this class).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文