使用正则表达式验证

时间:2014-04-16 00:14:32

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

我在ASP.net MVC项目中使用RegularExpression属性时遇到了一些问题。

它似乎在客户端工作,它在适合时消失,然后在后期操作时,检查模型状态是否有效,它最终发布错误,它必须遵循正则表达式。

我试过以下:

^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}$

^\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{1,2}$

基本上它必须以14/12/2014 14:20作为输入。

有什么想法吗?我输了。

型号:

[Required]
[Display(Name = "TimeDisplay", ResourceType = typeof(Resources.Models.Log))]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
[RegularExpression(@"^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}$")]
public DateTime Time { get; set; }

控制器操作:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Log log)
{
    if (ModelState.IsValid)
    {
        db.Logs.Add(log);
        db.SaveChanges();
        TempData["Notification"] = AlertGenerator.GenerateAlert(AlertGenerator.Level.Success, "Success! Log Saved");
        return RedirectToAction("Index");
    }

    return View(log);
}

1 个答案:

答案 0 :(得分:0)

据我所知,MVC将使用当前的CultureInfo(在服务器上)来解析DateTime格式,因此您无法直接绑定" dd / MM / yyyy HH:mm"到你的实体。

我的解决方案是创建ViewModel,然后使用DateTime.ParseExact(...)来解析日期:

型号:

[Display(Name = "TimeDisplay", ResourceType = typeof(Resources.Models.Log))]
[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
public DateTime Time { get; set; }

视图模型

[Display(Name = "TimeDisplay", ResourceType = typeof(Resources.Models.Log))]
[Required]
public string Time { get; set; }

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(LogViewModel logViewModel)
{
    if (ModelState.IsValid)
    {
        // convert from ViewModel to Entity Model
        Log log = new Log(logViewModel);
        // parse the time
        log.Time = DateTime.ParseExact(logViewModel.Time, "dd/MM/yyyy HH:mm", null);

        db.Logs.Add(log);
        db.SaveChanges();
        TempData["Notification"] = AlertGenerator.GenerateAlert(AlertGenerator.Level.Success, "Success! Log Saved");
        return RedirectToAction("Index");
    }

    return View(log);
}
相关问题