使用DataAnnotations绑定自定义格式的时间跨度

时间:2018-07-30 11:33:55

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

我正在使用EF Core构建ASP.Net Core 2.1 MVC Web应用程序。我有一个具有TimeSpan属性的模型。我希望输入的时间(mm:ss)在01:0059:59之间,所以我不想显示TimeSpan的小时部分,因为无论如何它都是零。为此,我在属性中添加了DisplayFormat属性。因为我想进行客户端验证,所以我也添加了RegularExpression属性:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:mm\:ss}")]
[RegularExpression(@"((0?0:)?([0-3]?[0-9])(:[0-5][0-9])?)", ErrorMessage = "Die Dauer muss zwischen 01:00 und 30:00 liegen")]
public TimeSpan SlotDuration { get; set; }

(我确实知道我的正则表达式不会验证至少一分钟的事情,但这不是我的意思。)

现在,我确实遵守以下规定:

  1. 为具有20分钟插槽时间的实体加载我的 Edit 页面时,将按预期显示20:00。如果我提交请求,则模型验证失败,并显示正则表达式属性的ErrorMessage。
  2. 执行与(1)中相同的操作,但是输入0:20:00是可行的,ModelState.IsValid == true并且SlotDuration绑定值正确。
  3. 如果删除regex属性,则对于0:20:00的验证和绑定可以正常工作;使用20:00会导致20小时的时间跨度。
  4. 以下代码输出 20:00 --> 00:20:00 match

    string value = null;
    TimeSpan interval;
    var rg = new System.Text.RegularExpressions.Regex(@"((0?0:)?([0-3]?[0-9])(:[0-5][0-9])?)");
    value = "10:25";
    if (TimeSpan.TryParseExact(value, @"mm\:ss", null, out interval))
        Console.WriteLine("{0} --> {1}", value, interval.ToString("c"));
    else
        Console.WriteLine("Unable to parse '{0}'", value);
    if (rg.IsMatch(value))
        Console.WriteLine("match");
    else
        Console.WriteLine("no match");
    

问题:

  • 即使正则表达式匹配并且为什么可以将字符串解析为TimeSpan,即使不是按照我想要的方式,为什么验证也会失败?
  • 如何使ModelBinder使用我的DisplayFormat将输入的值转换为TimeSpan?是否有另一个实现此目的的属性/属性/...?

0 个答案:

没有答案
相关问题