c# - 要么或要求验证

标签 c# asp.net-mvc-3 validation unobtrusive-validation

我想使用 ComponentModel DataAnnotations 验证两个属性中至少有一个具有值。我的模型如下所示:

public class FooModel {
   public string Bar1 { get; set; }
   public int Bar2 { get; set; }
}

基本上,我想验证 FooModel,以便需要 Bar1 Bar2。换句话说,您可以输入一个或另一个,或两者都输入,但不能将它们都留空。

我希望这既适用于服务器端验证,也适用于不显眼的客户端验证。


编辑:这可能是一个 possible duplicate, as this looks similar to what I'm looking to do

最佳答案

如果您想使用自定义 JavaScript 来执行验证,则需要扩展 ValidationAttribute 类并覆盖 IsValid 方法,并实现 IClientValidatable。如下所示。

[AttributeUsage(AttributeTargets.Property)]
    public sealed class AtLeastOneOrTwoParamsHasValue : ValidationAttribute, IClientValidatable
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var param1 = validationContext.ObjectInstance.GetType().GetProperty("Param1").GetValue(value, null);
            //var param2 = validationContext.ObjectInstance.GetType().GetProperty("Param2").GetValue(value, null);

            //DO Compare logic here.

            if (!string.IsNullOrEmpty(Convert.ToString(param1)))
            {
                return ValidationResult.Success;
            }


            return new ValidationResult("Some Error");
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            //Do custom client side validation hook up

            yield return new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.DisplayName),
                ValidationType = "validParam"
            };
        }
    }

用法:

[AtLeastOneOrTwoParamsHasValue(ErrorMessage="Atleast one param must be specified.")]

关于c# - 要么或要求验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9560227/

相关文章:

c# - gdi+ - Graphics.MeasureString 太宽或太窄

c# - 在变量 C# 中保存 richTextBox 的特定行

asp.net-mvc-3 - CaSTLe.Windsor,ASP.NET MVC,处理注入(inject)的空解析

asp.net-mvc-3 - 匿名类型成员声明符无效。匿名类型成员必须使用成员赋值、简单名称或成员访问进行声明

html - 编码 HTML 的正则表达式

正则表达式:查找两个未知标签之间的文本

c# - ListView 作为日志文件

asp.net-mvc - 通过示例学习ASP MVC。奖励: an example that uses MVVM in microsoft's MVC framework

php - 修剪空格后在 jQuery 数据表中进行内联编辑验证

c# - 比较两个日期时间,一个来自 Datetimepicker,一个来自 MySql 数据库