如何比较模型 属性 的不平等与 MVC 模型中的多个字段

How to compare a model property for No Equality with multiple fields in Model in MVC

我是 MVC 技术的新手。今天我接到一个任务,要制作一个表格,用户可以在表格上输入多个电子邮件地址。我需要阻止用户在其他文本框中输入重复的电子邮件地址。我创建了一个用于比较的自定义验证器,名为 "NonEqualValidation",如下所示

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class NonEqualValidation : ValidationAttribute, IClientValidatable
{
    private const string DefaultErrorMessage = "Duplicate e-mail not allowed";
    public string OtherProperty { get; private set; }
    public string OtherPropertyName { get; private set; }

    public NonEqualValidation(string otherProperty, string otherPropertyName): base(DefaultErrorMessage)
    {
        OtherProperty = otherProperty;
        OtherPropertyName = otherPropertyName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(OtherProperty);

            var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);

            if (value.Equals(otherPropertyValue))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
        }

        return ValidationResult.Success;

    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule()
        {
            ValidationType = "unlike",
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
        };

        rule.ValidationParameters.Add("otherproperty", OtherProperty);
        rule.ValidationParameters.Add("otherpropertyname", OtherPropertyName);

        yield return rule;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, OtherPropertyName);
    }
}

我的模型结构如下:

 [EmailAddress(ErrorMessage = "Please enter valid e-mail address")]
    [NonEqualValidation("MAILFRIEND2", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND3", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND4", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND5", "Duplicate e-mail not allowed")]
    public string MAILFRIEND1 { get; set; }

    [EmailAddress(ErrorMessage = "Please enter valid e-mail address")]
    [NonEqualValidation("MAILFRIEND1", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND3", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND4", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND5", "Duplicate e-mail not allowed")]
    public string MAILFRIEND2 { get; set; }

    [EmailAddress(ErrorMessage = "Please enter valid e-mail address")]
    [NonEqualValidation("MAILFRIEND1", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND2", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND4", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND5", "Duplicate e-mail not allowed")]
    public string MAILFRIEND3 { get; set; }

    [EmailAddress(ErrorMessage = "Please enter valid e-mail address")]
    [NonEqualValidation("MAILFRIEND1", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND2", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND3", "Duplicate e-mail not allowed")]
    [NonEqualValidation("MAILFRIEND5", "Duplicate e-mail not allowed")]
    public string MAILFRIEND4 { get; set; }

    [EmailAddress(ErrorMessage = "Please enter valid e-mail address")]
    [NonEqualValidation("MAILFRIEND1", "E-mail is use above")]
    [NonEqualValidation("MAILFRIEND2", "E-mail is use above")]
    [NonEqualValidation("MAILFRIEND3", "E-mail is use above")]
    [NonEqualValidation("MAILFRIEND4", "E-mail is use above")]
    public string MAILFRIEND5 { get; set; }

但还是没有得到预期的结果。如果我也输入重复值,因为它不起作用。有人可以帮忙吗。

我也添加了此 jquery 验证,以便在客户端进行验证,如下所示 post.I 我无法将其粘贴为错误:

http://macaalay.com/2014/02/25/unobtrusive-client-and-server-side-not-equal-to-validation-in-mvc-using-custom-data-annotations/

您可以使用远程验证。 型号

[Remote("doesEmailExist", "Email", HttpMethod = "Post", ErrorMessage = "Email already exist.")]
        public string Email { get; set; }

在控制器中

[HttpPost]
        public JsonResult doesEmailExist([Bind(Prefix = "Email.EmailName")]string EmailName)
        {
            var email = db.Emails.FirstOrDefault(a => a.EmailName == EmailName);
            return Json(email == null);
        }

希望这会有所帮助..

你很接近。

自定义属性实现: 与其从头开始实施新的自定义属性,不如创建一个派生自 CompareAttribute 的属性。然后覆盖 IsValid 方法。

型号: 由于您有 5 个电子邮件属性,我会在每封电子邮件 属性 上放置一个 CustomAttribute 以检查另一封电子邮件 属性。

像这样:

[EmailAddress(ErrorMessage = "Please enter valid e-mail address")]
[NonEqualValidation("MAILFRIEND5", "Duplicate e-mail not allowed")]
public string MAILFRIEND1 { get; set; }

[EmailAddress(ErrorMessage = "Please enter valid e-mail address")]
[NonEqualValidation("MAILFRIEND1", "Duplicate e-mail not allowed")]
public string MAILFRIEND2 { get; set; }

[EmailAddress(ErrorMessage = "Please enter valid e-mail address")]
[NonEqualValidation("MAILFRIEND2, "Duplicate e-mail not allowed")]
public string MAILFRIEND3 { get; set; }

[EmailAddress(ErrorMessage = "Please enter valid e-mail address")]
[NonEqualValidation("MAILFRIEND3, "Duplicate e-mail not allowed")]
public string MAILFRIEND4 { get; set; }

[EmailAddress(ErrorMessage = "Please enter valid e-mail address")]
[NonEqualValidation("MAILFRIEND4, "Duplicate e-mail not allowed")]
public string MAILFRIEND5 { get; set; }

这是一个示例自定义属性。

您可以将要比较的属性添加为逗号分隔的字符串。

 public class CompareNotEqualAttribute : ValidationAttribute
{


    public List<string> CompareProperties { get; set; }
    public CompareNotEqualAttribute(string compareproperty)
    {
            CompareProperties = compareproperty.Split(',').ToList();
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        foreach(var compareProperty in CompareProperties)
        {
            var otherProperty = validationContext.ObjectType.GetProperty(compareProperty);
            if (otherProperty == null)
                return new ValidationResult(String.Format("Unknown property: {0}.", otherProperty));
            // get the other value
            var other = otherProperty.GetValue(validationContext.ObjectInstance, null);

            if (other.Equals(value))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            else
            {
                return null;
            }
        }
        return null;
    }
}

你可以实现这个:

 public class CompareNotEqualAttribute : ValidationAttribute
{

    public List<string> CompareProperties { get; set; }

    public CompareNotEqualAttribute(string compareproperty)
    {
            CompareProperties = compareproperty.Split(',').ToList();
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        foreach(var compareProperty in CompareProperties)
        {
            var otherProperty = validationContext.ObjectType.GetProperty(compareProperty);
            if (otherProperty == null)
                return new ValidationResult(String.Format("Unknown property: {0}.", otherProperty));
            // get the other value
            var other = otherProperty.GetValue(validationContext.ObjectInstance, null);

            if (other.Equals(value))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            else
            {
                return null;
            }
        }
        return null;
    }
}

并在您的属性中列出其他电子邮件地址,以逗号分隔。