【问题标题】:Custom Validation on Multiple Inputs in ASP.net MVCASP.net MVC 中多个输入的自定义验证
【发布时间】:2015-09-18 20:12:23
【问题描述】:

在研究了在 MVC 中实现自定义表单验证规则的各种方法后,我发现,我最初认为是一种简单的验证,比我预期的要复杂得多。

我有 2 个文本输入,需要填充一个或另一个(或两者)。如果两者都是NullOrEmpty,我们需要抛出一个错误。

我发现DataAnnotations 在尝试验证多个字段时有其局限性,让我在两个输入上都突出显示并抛出一个错误。这是一些初学者的天真吗?

我也玩过FluentValidation,但无法得到我想要的结果。

目前我正在使用以下方法在控制器中抛出错误:

ModelState.AddModelError("PropertyName", "You need to enter a Property Number or a Property Name")
ModelState.AddModelError("PropertyNumber", String.Empty)

这让我强调了字段和服务器端验证。我现在发现在不使用 DataAnnotations 的情况下很难绑定自定义客户端验证。

有人对如何正确执行此操作有任何建议吗?任何帮助或建议将不胜感激。我需要在服务器/客户端上验证两个字段,突出显示和一条错误消息。

提前致谢。

【问题讨论】:

  • 我用这个fluentvalidation.codeplex.com..你检查了吗?

标签: asp.net-mvc validation data-annotations


【解决方案1】:

[万无一失][1]验证库涵盖了几乎所有类型的验证场景。

[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]

Applied to a Model:

public class CreateUserViewModel
{
    [Required]
    public string Username { get; set; }

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

    [RequiredIfEmpty(ErrorMessage="error message"]
    public string Role { get; set; }
}

【讨论】:

    猜你喜欢
    • 2017-06-21
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多