2017-06-29 8 views
-3

datetimeフィールドのカスタム検証を作成したいとします。カスタム検証日付c#

私のクラスの予約がフィールド私は検証を置くしたい "日付" と、あります:

public class Booking 
    { 
     public int Id { get; set; } 
     public int Restochoisi { get; set; } 
     public int Nbpeople { get; set; } 
     [CustomValidator] 
     public DateTime Date { get; set; } 
     public int Orga { get; set; } 
    } 

クラスCustomValidator.cs:

[AttributeUsage(AttributeTargets.Property | 
    AttributeTargets.Field, AllowMultiple = false)] 
public class CustomValidator : ValidationAttribute 
{ 
    protected override bool IsValid(object value) 
    { 
     if ((DateTime)value < DateTime.Now) 
      return false; 
     return true; 
    } 

} 

とBookingController:

[HttpPost] 
    public ActionResult Index(int restochoisi, int nbpeople, DateTime start, int orga) 

    { 
     var context = new BddContexte(); 

     var vm = new BookingViewModel() 
     { 
      Restos = new SelectList(context.Restos.AsEnumerable(), "Id", "Nom"), 
      Utilisateurs = new SelectList(context.Utilisateurs.AsEnumerable(), "Id", "Prenom") 

     }; 

     //ViewBag.result = restochoisi + " " + nbpeople + " " + datepicker + " " + orga; 
     //dal.RestoById(restochoisi) 
     if (ModelState.IsValid) 
     { 
      int id = dal.CreerBooking(restochoisi, nbpeople, start, orga); 
      return View(vm); 
     } 
     return View(vm); 
    } 

しかし、動作しません。私の歩き方で何が間違っていますか?

+2

正確には機能しません。間違いはありますか?エラーはありませんか? – Mederic

+0

「間違った」日付を入力すると、「CreerBooking」という関数でエラーが発生します。 –

答えて

0

あなたのコントローラはそのなしでバリ

[HttpPost] 
public ActionResult Index(Booking booking) 
{ 
    // snip 
} 

であなたのモデルクラスを使用する必要があり、私はあなたのカスタムバリデータが作業すると思うかどうかはわかりません!

+0

この変更では、私はエラーはありませんが、日付が正しい場合でもモデルステートは常にfalseです。 –

+0

@MatthieuVeron - 'ModelState'はあなたのモデルについて正しくないものを教えてくれます。修理する。 – Jamiec

+0

?? これはまさに私の質問の目的です。私は自分のコードで何が間違っているのか分かりません。モデルステートは 'ModelState.IsValid'がfalseのときに返すようなものを返しません。 –