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

本文介绍如何在ASP.NET MVC中通过自定义验证属性实现字段唯一性检查,确保输入数据的唯一性和有效性。通过实例展示了如何创建一个名为`NameAndBearchValidation`的自定义验证规则,用于验证`comName`字段是否与其他字段值唯一。
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; }
    }
}

  

转载于:https://www.cnblogs.com/liuchang/p/4514860.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值