MVC驗證13-2個屬性至少輸入一項

來源:互聯網
上載者:User

標籤:des   style   blog   class   code   java   

有時候,我們希望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; }
    }
}

如果讓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;
        }
    }
}
 

 

□ 把自訂特性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; }
    }
}
 

 

□ 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);
            }
        }
    }

 

□ 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>
 

 

□ 效果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.