【问题标题】:Required field - conditional expression/validation必填字段 - 条件表达式/验证
【发布时间】:2014-02-23 08:39:52
【问题描述】:

我想知道如何对 DateTime 属性设置条件要求。也就是说,除了检查此必填字段是否为空之外,我希望输入(在 cshtml 文件中)不早于今天起 3 周。

型号:

[DataType(DataType.Date)]
[Display(Name = "Start date"), Required(ErrorMessage = ValidationMessages.IsRequired)]
//[What else here for this condition??]
public DateTime StartDate { get; set; }

.cshtml:

<div class="form-group">
    <div class="editor-label">
        @Html.LabelFor(model => model.Assignment.StartDate)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Assignment.StartDate)
        @Html.ValidationMessageFor(model => model.Assignment.StartDate)
    </div>
</div>

这样的条件表达式会是什么样子?除了模型中的条件之外,我还需要添加一些东西吗?

如果我的描述太少,请说出来。

// 提前致谢,问候

【问题讨论】:

标签: c# .net asp.net-mvc


【解决方案1】:

您可以创建自己的验证属性,如下所示:

1) 带有自定义错误消息的自定义验证属性

public class CheckInputDateAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var inputDate = (DateTime)value;
        var compareDate = DateTime.Now.AddDays(21);
        int result = DateTime.Compare(inputDate, compareDate);
        const string sErrorMessage = "Input date must be no sooner than 3 weeks from today.";
        if (result < 0)
        {
            return new ValidationResult(sErrorMessage);
        }
        return ValidationResult.Success;
    }
}

然后像这样使用它

  [DataType(DataType.Date)]
  [CheckInputDate]
  public DateTime StartDate { get; set; }

2) 没有自定义错误消息的自定义验证属性

public class CheckInputDateAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var inputDate = (DateTime)value;
        var compareDate = DateTime.Now.AddDays(21);
        int result = DateTime.Compare(inputDate, compareDate);
        return result >= 0;
    }
}

然后像这样使用它

    [DataType(DataType.Date)]
    [Display(Name = "Start date")]   
    [CheckInputDate]
    public DateTime StartDate { get; set; }

【讨论】:

  • 谢谢,我会试试的。
  • 谢谢,这很好用。但是,我因为没有弄清楚这一点而感到有点愚蠢。而不是显示属性名称和消息:“[Assignment.StartDate] = 输入日期必须不早于今天起 3 周。”,我想显示显示名称和错误消息。
  • 嗨,很抱歉回复晚了。但是您更新的答案修复了它。谢谢,这篇文章可以设置为“已解决”。
【解决方案2】:

您可以在模型中执行此操作。添加适当的错误消息。

[Required(ErrorMessage = "")]

[Range(typeof(DateTime), DateTime.Now.ToString(), DateTime.Now.AddDays(21).ToString(), ErrorMessage = "" )]

public DateTime StartDate { get; set; }

【讨论】:

  • 如果我错了,请纠正我,但这不会产生编译错误:“属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式”?
  • 我会试试的。不过要到明天才能试。一个问题,这看起来必须在今天和未来三周之间,我错了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-15
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多