2011-01-20 20 views

答えて

161

はここで続行する方法です、それはIClientValidatableを実装する方法

public class FutureDateAttribute : ValidationAttribute, IClientValidatable 
{ 
    public override bool IsValid(object value) 
    { 
     if (value == null || (DateTime)value < DateTime.Now) 
      return false; 

     return true; 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     yield return new ModelClientValidationRule 
     { 
      ErrorMessage = this.ErrorMessage, 
      ValidationType = "futuredate" 
     }; 
    } 
} 

注意してください。そして、コントローラ

public class MyViewModel 
{ 
    [FutureDate(ErrorMessage = "Should be in the future")] 
    public DateTime Date { get; set; } 
} 

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(new MyViewModel 
     { 
      // intentionally put in the past 
      Date = DateTime.Now.AddDays(-1) 
     }); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     return View(model); 
    } 
} 

し、最終的にビュー:

@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(x => x.Date) 
    @Html.TextBoxFor(x => x.Date) 
    @Html.ValidationMessageFor(x => x.Date) 
    <input type="submit" value="OK" /> 
} 

魔法が起こるためには最後の部分は、カスタムアダプタを定義することです次に、我々は我々のモデルを書きます:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script> 
<script type="text/javascript"> 
    // we add a custom jquery validation method 
    jQuery.validator.addMethod('greaterThan', function (value, element, params) { 
     if (!/Invalid|NaN/.test(new Date(value))) { 
      return new Date(value) > new Date($(params).val()); 
     } 
     return isNaN(value) && isNaN($(params).val()) || (parseFloat(value) > parseFloat($(params).val())); 
    }, ''); 

    // and an unobtrusive adapter 
    jQuery.validator.unobtrusive.adapters.add('futuredate', { }, function (options) { 
     options.rules['greaterThan'] = true; 
     options.messages['greaterThan'] = options.message; 
    }); 
</script> 
+3

鮮やかな答え! – raklos

+0

ほとんどの作業 - 日付はどのような形式ですか? – raklos

+1

@raklosは、ブラウザーとサーバーのローカライズ設定に依存します。違いがある場合は、1つのフォーマットがクライアントの検証に合格する可能性はありますが、サーバの検証には合格する可能性があります。また、あなたの日付がどのような形式であるかを決めることはあなた次第です。 –

4

あなたの質問を頼まれましたが、あなたはまだ、メタデータのような場合、あなたはまだ単純化された選択肢のために開いている、あなたは以下のアノテーションを使用して、あなたの問題を解決することができるのでながら少し:

[Required] 
[AssertThat("Date > Now()")] 
public DateTime? Date { get; set; } 

これは、両方のために働く - サーバとクライアント、箱から出してください。詳細はExpressiveAnnotationsライブラリをご覧ください。

+0

あなたのライブラリーで1日を保存しました。使い方が簡単でとても便利です。ありがとう – Maco

関連する問題