码迷,mamicode.com
首页 > 其他好文 > 详细

自定义验证(判断两个值同时唯一)

时间:2015-05-19 18:10:34      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Web;
using BLL.BLL;

namespace www.nabian.com.Models
{
    public class NameAndBearchValidation : ValidationAttribute
    {
        RegisterManagerBLL manager = new RegisterManagerBLL();
        public string OtherProperty { get; set; }
        public string OtherPropertyDisplayName
        {
            [CompilerGenerated]
            get
            {
                return OtherPropertyDisplayName;
            }
            [CompilerGenerated]
            internal set
            {
            }
        }
        public override bool RequiresValidationContext
        {
            get
            {
                return RequiresValidationContext;
            }
        }
        public NameAndBearchValidation(string otherProperty)
        {
            if (otherProperty == null)
                throw new ArgumentNullException("otherProperty");

            OtherProperty = otherProperty;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var property = validationContext.ObjectType.GetProperty(OtherProperty);
            var other = property.GetValue(validationContext.ObjectInstance, null);
            if (manager.QueryComName(value.ToString()) <= 0 && manager.QueryComName(other.ToString(), value.ToString()) <= 0)
            {
                return ValidationResult.Success;
            }
            return ValidationResult.Success;
        }
    }
}

  测试

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using www.nabian.com.Models;

namespace www.nabian.com.ViewsModels
{
    public class textModel
    {
        [NameAndBearchValidation("comName", ErrorMessage = "两个属性不唯一")]
        public string name { get; set; }

        public string comName { get; set; }
    }
}

  

自定义验证(判断两个值同时唯一)

标签:

原文地址:http://www.cnblogs.com/liuchang/p/4514860.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!