【问题标题】:asp.net mvc validation on 2 fields - one must exist if other entered对 2 个字段进行 asp.net mvc 验证 - 如果输入其他字段,则必须存在一个
【发布时间】:2012-02-21 03:04:18
【问题描述】:

我的视图模型中有 2 个文本字段,text1 和 text2。我需要验证是否输入了 text1,然后必须输入 text2,反之亦然。在视图模型的自定义验证中如何实现这一点?

谢谢。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 validation


    【解决方案1】:

    您可以使用实现 IValidatableObject(来自 System.ComponentModel.DataAnnotations 命名空间)在您的视图模型上进行服务器端验证:

    public class AClass : IValidatableObject 
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string SecondName { get; set; }
            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
            {
                if( (!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(SecondName)) || (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(SecondName)) )
                    yield return new ValidationResult("Name and Second Name should be either filled, or null",new[] {"Name","SecondName"});
            }
        }
    

    现在它确定是否同时设置了 Name 和 SecondName,或者为 null,则模型有效,否则无效。

    【讨论】:

    • 仅供参考,我建议在使用验证摘要时不要返回验证结果中的字段。如果您在验证结果中返回两个字段,则验证摘要将包含两条消息,而不是预期的单个消息。
    • 能否请您提供一些代码来说明如何使用它来注释类属性?
    【解决方案2】:

    查看 mvc 万无一失的验证,它会进行条件验证。在 nuget 或 http://foolproof.codeplex.com

    上找到它

    编辑 以上真的很老了

    我建议任何现代的东西都使用 MVC Fluent Validation https://docs.fluentvalidation.net/en/latest/aspnet.html

    【讨论】:

    • 这已经很老了,我不会推荐
    【解决方案3】:

    你可以使用 JQuery,像这样:

    $("input[x2]").hide();
        $("input[x1]").keypress(function() {
              var textValue = ("input[x1]").val();
             if(textValue) 
                          $("input[x2]").show();
            })
    

    【讨论】:

      【解决方案4】:

      如果你想在你的模型上使用数据注释验证器和验证属性,你应该看看这个: "attribute dependent on another field"

      【讨论】:

        猜你喜欢
        • 2019-05-15
        • 2022-12-14
        • 1970-01-01
        • 1970-01-01
        • 2019-01-07
        • 2012-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多