【问题标题】:MVC Compare email if confirm field is not empty如果确认字段不为空,MVC 比较电子邮件
【发布时间】:2016-12-13 13:39:16
【问题描述】:

只有当字段不为空时,有没有办法触发比较数据注释?如果没有,还有什么方法可以做到?

下面的这段代码总是触发比较数据注释,不管它是否有值。

[EmailAddress]
[Required]
[Display(Name = "Email Address")]
public string EmailAddress { get; set; }

[Display(Name = "Confirm Email Address")]
[Compare("EmailAddress", ErrorMessage = "The email addresses do not match.")]
public string ConfirmEmailAddress { get; set; }

【问题讨论】:

  • 请注意,model-view-controller 标签是针对有关模式的问题。 ASP.NET-MVC 实现有一个特定的标记。
  • @StephenMuecke。哦,好吧...我看到您已经编辑了标签。明白了。

标签: c# asp.net-mvc data-annotations email-validation


【解决方案1】:

用你自己的扩展属性可能是最简单的:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class CompareEnhancedAttribute : CompareAttribute
{
    public bool AllowEmptyStrings { get; set; }

    public CompareEnhancedAttribute(string otherProperty)
        : base(otherProperty)
    {
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (AllowEmptyStrings && string.IsNullOrEmpty(value?.ToString()))
        {
            return ValidationResult.Success;
        }
        else
        {
            return base.IsValid(value, validationContext);
        }
    }
}

然后像这样使用它:

public sealed class ContactModel
{
    /* omitted other attributes */

    public string EmailAddress { get; set; }

    [CompareEnhanced("EmailAddress", AllowEmptyStrings = true)]
    public string ConfirmEmailAddress { get; set; }
}

【讨论】:

    猜你喜欢
    • 2011-11-07
    • 2016-08-06
    • 2020-06-16
    • 2018-07-31
    • 2011-09-19
    • 2012-08-10
    • 2022-01-24
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多