原文:MVC验证13-2个属性至少输入一项

有时候,我们希望2个属性中,至少有一个是必填,比如:

using Car.Test.Portal.Extension;
 
namespace Car.Test.Portal.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string Telephone { get; set; }
        public string Address { get; set; }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

如果让Telephone和Address属性中,有一个是必填项,需要自定义特性。

 

□ 自定义AtLeastOneAttribute特性,派生于ValidationAttribute类,并实现IClientValidatable接口

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;
 
namespace Car.Test.Portal.Extension
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public sealed class AtLeastOneAttribute : ValidationAttribute, IClientValidatable
    {
        public string PrimaryProperty { get; private set; }
        public string SecondaryProperty { get; private set; }
 
        public AtLeastOneAttribute(string primaryProperty, string secondProperty)
        {
            PrimaryProperty = primaryProperty;
            SecondaryProperty = secondProperty;
        }
 
        public override string FormatErrorMessage(string name)
        {
            return string.Format(CultureInfo.CurrentCulture, this.ErrorMessageString, PrimaryProperty, SecondaryProperty);
        }
 
        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            object primaryValue = properties.Find(PrimaryProperty, true /* ignoreCase */).GetValue(value);
            object secondaryValue = properties.Find(SecondaryProperty, true /* ignoreCase */).GetValue(value);
            if (primaryValue != null || secondaryValue != null)
            {
                return true;
            }
            else
            {
                return false;
            }
            //return (primaryValue != null || secondaryValue != null);
 
            //稍稍改动以下还可以比较2个属性是否相等
            //if (!primaryValue.Equals(secondaryValue))
            //    return true;
            //else
            //    return false;
        }
 
        public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            string errorMessage = FormatErrorMessage("");
            ModelClientValidationRule rule = new ModelClientValidationRule()
            {
                ValidationType = "atleastone",
                ErrorMessage = errorMessage
            };
            rule.ValidationParameters.Add("primary", this.PrimaryProperty);
            rule.ValidationParameters.Add("secondary", this.SecondaryProperty);
            yield return rule;
        }
    }
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ 把自定义特性AtLeastOneAttribute打到类上

using Car.Test.Portal.Extension;
 
namespace Car.Test.Portal.Models
{
    [AtLeastOne("Telephone", "Address",ErrorMessage = "Telephone和Address至少填一项~~")]
    public class Person
    {
        public int Id { get; set; }
        public string Telephone { get; set; }
        public string Address { get; set; }
    }
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ PersonController

    public class PersonController : Controller
    {
        public ActionResult Index()
        {
            return View(new Person());
        }
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(Person person)
        {
            if (ModelState.IsValid)
            {
                //TODO:
                return Content("ok");
            }
            else
            {
                return View(person);
            }
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ Person/Index.cshtml

需要把自定义的特性注册到jquery相关类库中。

@model Car.Test.Portal.Models.Person
 
<body>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery-migrate-1.2.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    @*<script src="~/Scripts/atleastone.js"></script>*@
    <style type="text/css">
        .validation-summary-errors {
            color: red;
        }
    </style>
    <script type="text/javascript">
        jQuery.validator.addMethod("atleastone", function (value, element, params) {
            var primaryProperty = params.primary;
            var secondaryProperty = params.secondary;
 
            if (primaryProperty.length > 0 || secondaryProperty.length > 0) {
                return true;
            } else {
                return false;
            }
        });
 
        jQuery.validator.unobtrusive.adapters.add("atleastone", ["primary", "secondary"], function (options) {
            options.rules["atleastone"] = {
                primary: options.params.primary,
                secondary: options.params.secondary
            };
            options.messages["atleastone"] = options.message;
        });
        
    </script>
    
    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
       
    
        <fieldset>
            <legend>Person</legend>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Telephone)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Telephone)
                @Html.ValidationMessageFor(model => model.Telephone)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Address)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Address)
                @Html.ValidationMessageFor(model => model.Address)
            </div>
    
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    }
 
</body>
</html>
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ 效果

最新文章

  1. 11g新特性-概述 (转)
  2. POJ 2155 Matrix (二维线段树)
  3. 如何在Netbeans中查看TODO项
  4. 【转载】 c语言inline函数的使用
  5. Andstudio更新失败的解决办法。
  6. VS2010如何生成release文件
  7. php抽奖概率算法(刮刮卡,大转盘)
  8. mybatis快速入门(五)
  9. BZOJ_1334_[Baltic2008]Elect_DP+语文题
  10. 深入学习Redis(5):集群
  11. Day10 空时编码理论之无线信道、分集和复用
  12. Neutron local network 学习
  13. 使用Vlc.DotNet打开摄像头并截图 C#
  14. Hive数仓之快速入门(二)
  15. Java代码优化小结(二)
  16. Oracle 19C的下载和安装部署(图形安装和静默安装)
  17. 积累的关于linux的安装卸载软件基本命令
  18. emmc基础技术8:操作模式3-interrupt mode
  19. 洛谷P4425 转盘 [HNOI/AHOI2018] 线段树+单调栈
  20. MySql SqlServer Sqlite中关于索引的创建

热门文章

  1. 【Java基础】System.arraycopy()的使用详解
  2. Swift UI学习UITableView and protocol use
  3. 终端查询数据库sqlite(创建你自己,或者是coredata创建)那里的东西
  4. 一个非常有用的函数——COALESCE
  5. NUnit3 Test Adapter vs2015
  6. nodejs 复制、移动文件
  7. Java 多线程编程两个简单的例子
  8. 怎么样sourceforge开源项目发现,centos安装-同htop安装案例
  9. Ajax基础知识(一)
  10. uva10067 Playing with Wheels 【建图+最短路】