using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Globalization;
namespace Mvc5App.Models
{
public class TimeSpanModel
{
[Required]
// クライアント側の検証を無効にすれば RangeAttribute でも可
//[Range(typeof(TimeSpan), "00:00:00", "00:59:59")]
[RegularExpression(@"^00:[0-5]\d:[0-5]\d$")]
public TimeSpan Start { set; get; }
[Required]
// クライアント側の検証を無効にすれば RangeAttribute でも可
//[Range(typeof(TimeSpan), "00:00:00", "00:59:59")]
[RegularExpression(@"^00:[0-5]\d:[0-5]\d$")]
public TimeSpan Stop { set; get; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using Mvc5App.Models;
using System.IO;
namespace Mvc5App.Controllers
{
public class HomeController : Controller
{
public ActionResult TimeSpanTest()
{
TimeSpanModel model = new TimeSpanModel
{
Start = new TimeSpan(0, 0, 0),
Stop = new TimeSpan(0, 59, 59)
};
return View(model);
}
[HttpPost]
public ActionResult TimeSpanTest(TimeSpanModel model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(model);
}
}
}
Model に付与した Rquired と RegularExpression での検証結果は以下のようになります。下の例ではエラーメッセージはデフォルトですが自由に設定できます。