MVC 3 验证 - 仅在失去焦点或提交后显示错误消息?

发布于 2024-11-08 23:04:40 字数 2813 浏览 0 评论 0原文

我已经使用 DataAnnotations(必需、字符串长度等)在 MVC 3 应用程序中设置了实体,并且 MVC 页面相应地显示了验证错误消息。但是,在用户有机会输入无效值之前,页面加载到新表单后就会显示错误消息。

几年前我曾使用过 JQuery 验证,并且只能在用户失去对字段的焦点或尝试提交表单后才显示错误消息。事实上,我认为这是默认行为。

无论如何,是否可以使用 DataAnnotations 在 MVC 3 中执行相同的操作?

编辑:这是 HTML

<div class="form horizontal floated w50p">
<h3>Billing Information</h3>
@using(Html.BeginForm()){
    <div class="item">
        <div class="label">
            <label>* First Name</label></div>
        <div class="value">@Html.TextBoxFor(x => x.Name)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.Name)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>* Address 1</label></div>
        <div class="value">@Html.TextBoxFor(x => x.Street1)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.Street1)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>Address 2</label></div>
        <div class="value">@Html.TextBoxFor(x => x.Street2)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>Address 3</label></div>
        <div class="value">@Html.TextBoxFor(x => x.Street3)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>City</label></div>
        <div class="value">@Html.TextBoxFor(x => x.City)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.City)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>State/Province/Region</label></div>
        <div class="value">@Html.TextBoxFor(x => x.StateProv)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.StateProv)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>Zip / Postal Code</label></div>
        <div class="value">@Html.TextBoxFor(x => x.PostalCode)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.PostalCode)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>* Contact Phone</label></div>
        <div class="value">@Html.TextBoxFor(x => x.ContactPhone)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.ContactPhone)</div>
    </div>        <input type="submit" value="Submit" />
}

I have setup the entities in my MVC 3 app with DataAnnotations (required, stringlength, etc) and the MVC page is showing validation error messages appropriately. But, the error messages are shown as soon as the page loads on a new form before the user has had the chance to enter an invalid value.

I had used JQuery validation a few years ago and was able to only show the error messages after the user lost focus on a field or attempted to submit the form. In fact, I think it was the default behavior.

Is there anyway to do the same in MVC 3 using DataAnnotations?

EDIT: Here is the HTML

<div class="form horizontal floated w50p">
<h3>Billing Information</h3>
@using(Html.BeginForm()){
    <div class="item">
        <div class="label">
            <label>* First Name</label></div>
        <div class="value">@Html.TextBoxFor(x => x.Name)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.Name)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>* Address 1</label></div>
        <div class="value">@Html.TextBoxFor(x => x.Street1)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.Street1)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>Address 2</label></div>
        <div class="value">@Html.TextBoxFor(x => x.Street2)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>Address 3</label></div>
        <div class="value">@Html.TextBoxFor(x => x.Street3)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>City</label></div>
        <div class="value">@Html.TextBoxFor(x => x.City)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.City)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>State/Province/Region</label></div>
        <div class="value">@Html.TextBoxFor(x => x.StateProv)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.StateProv)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>Zip / Postal Code</label></div>
        <div class="value">@Html.TextBoxFor(x => x.PostalCode)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.PostalCode)</div>
    </div>
    <div class="item">
        <div class="label">
            <label>* Contact Phone</label></div>
        <div class="value">@Html.TextBoxFor(x => x.ContactPhone)</div>
        <div class="value">@Html.ValidationMessageFor(x => x.ContactPhone)</div>
    </div>        <input type="submit" value="Submit" />
}

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

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

发布评论

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

评论(2

岁月如刀 2024-11-15 23:04:40

默认行为正是您所描述的(仅在字段失去焦点或提交表单后才应出现错误)。所以,你的视图或控制器一定有问题。具体来说,听起来验证器认为用户即使在第一次查看表单时也会发回。表单的第一个视图应该是 GET 而不是 POST。如果您粘贴控制器代码,可能会帮助我们更好地诊断它。

The default behavior is exactly what you describe (errors should appear only after a field loses focus or form is submitted). So, there must be something wrong with your view or controller. Specifically, it sounds like the validator thinks the user is posting back even on the first view of the form. The first view of the form should be a GET not a POST. If you paste your controller code, that might help us diagnose it better.

转角预定愛 2024-11-15 23:04:40

您的意思是启用客户端验证?当然,这很容易。只是:

  1. 创建一个视图模型
  2. ,装饰它,
  3. 创建控制器,
  4. 创建一个视图,
  5. 包括适当的 jquery 脚本

,所以让我们继续执行这些步骤。

视图模型:

public class ProductViewModel
{
    [Required] // <-- you could use any data annotation attributes you like
    public string Name { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new ProductViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(ProductViewModel model)
    {
        return View(model);
    }
}

视图:

@model ProductViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Name)
    @Html.EditorFor(x => x.Name)
    @Html.ValidationMessageFor(x => x.Name)
    <input type="search" value="OK" />
}

现在将该字段留空,假设在 web.config 中启用了客户端验证(默认情况下,当您使用以下命令创建新的 ASP.NET MVC 3 项目时,客户端验证将会触发):默认的 Visual Studio 模板):

<appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

如果您想处理自定义验证属性,您可以,但它可能是 更痛苦一点。一旦您面对现实世界的应用程序并意识到使用属性(数据注释)进行声明式验证的弱点,我强烈建议您查看 FluentValidation.NET

You mean like enabling client validation? Sure, that's easy. Just:

  1. create a view model
  2. decorate it
  3. create controller
  4. create a view
  5. include proper jquery scripts

So let's go ahead and follow those steps.

View model:

public class ProductViewModel
{
    [Required] // <-- you could use any data annotation attributes you like
    public string Name { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new ProductViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(ProductViewModel model)
    {
        return View(model);
    }
}

View:

@model ProductViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Name)
    @Html.EditorFor(x => x.Name)
    @Html.ValidationMessageFor(x => x.Name)
    <input type="search" value="OK" />
}

Now leave the field blank and client validation will trigger assuming it is enabled in web.config (which it is by default when you create a new ASP.NET MVC 3 project using the default Visual Studio template):

<appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

If you want to handle custom validation attributes you could but it might be a little more painful. And once you get yourself confronted to real world applications and realize the weaknesses of declarative validation using attributes (data annotations) I would strongly recommend you checking out FluentValidation.NET.

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