簡體   English   中英

MVC2客戶端驗證DateTime嗎?

[英]MVC2 Client-side validation for a DateTime?

您建議使用哪種方法在MVC的客戶端上驗證DateTime?

假設我有一個帶有名為DateOfBirth的屬性的模型,該屬性是一個DateTime ,就像這樣。

public class UserModel
{
    [DataType(DataType.Date)]
    public DateTime DateOfBirth {get;set;}
}

在視圖上,我有一個簡單的

<%: Html.LabelFor(model=>model.DateOfBirth) %>
<%: Html.EditorFor(model=>model.DateOfBirth) %>
<%: Html.ValidationMessageFor(model=>model.DateOfBirth) %>
<input type="submit" value="Submit" />

我可以使用Microsoft MVC驗證或jQuery驗證。 如何獲取DateTime以驗證客戶端?

我意識到DataTypeAttribute所做的所有事情都是提供格式提示,並且實際上並沒有做任何驗證(它將這部分留給了ModelBinder)。

基本上,我想復制ModelBinder嘗試將發布的值放入模型的DateOfBirth屬性時的操作。

您有什么建議?

如上所述,請遵循Phil Haack關於自定義驗證的文章: http : //haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

這是我的處理方式:


  1. 添加一個“ DateFormatAttribute”類,如下所示:

    public class DateFormatAttribute : ValidationAttribute {
      public override bool IsValid(object value) {    
        if (value == null) {
          return true;
        }

        // Note: the actual server side validation still has to be implemented :-)
        // Just returning true now...

        return true;
      }
    }

  1. 添加一個“ DateFormatValidator”類,如下所示:

    public class DateFormatValidator : DataAnnotationsModelValidator 
    {
      string message;

      public PriceValidator(ModelMetadata metadata, ControllerContext context
        , DateFormatAttribute attribute)
        : base(metadata, context, attribute) 
      {
        message = attribute.ErrorMessage;
      }

      public override IEnumerable GetClientValidationRules() 
      {
        var rule = new ModelClientValidationRule {
          ErrorMessage = message,
          ValidationType = "date" // note that this string will link to the JavaScript function we'll write later on
        };

        return new[] { rule };
      }
    }

  1. 在Global.asax.cs中的某處注冊上述類:

    DataAnnotationsModelValidatorProvider
        .RegisterAdapter(typeof(DateFormatAttribute), typeof(DateFormatValidator));

  1. 在客戶端上添加驗證功能。 請注意,這必須在用戶的語言環境中實現。 以下是荷蘭語(nl-NL,nl-BE)客戶端驗證功能:

    /*
     * Localized default methods for the jQuery validation plugin.
     * Locale: NL
     */
    jQuery.extend(jQuery.validator.methods, {
        date: function(value, element) {
            return this.optional(element) || /^\d\d?[\.\/-]\d\d?[\.\/-]\d\d\d?\d?$/.test(value);
        }
    });

那應該涵蓋...

喬希

您的問題是MVC中的一個普遍問題,這是Modelbinder試圖將輸入的值從表單綁定到模型中。 顯然,如果它不適合,您將立即得到一個錯誤。

那么如何使Modelbinder使用我的自定義驗證? 並返回我的錯誤信息?

好吧,首先閱讀並做由phil haack寫的事情。 那么您就可以進行自定義驗證了。

接下來是。 不要在模型中使用整數和日期時間! 如果用戶可以在文本框中輸入任何內容,這總是會帶來問題。

您應該做的是,使對象成為flatObject。

flatObject非常簡單。 它是一個對象,內部變量的精確副本,僅inst和datetimes是字符串(cos始終綁定在modelbinder中)

例:

namespace MVC2_NASTEST.Models {

    public partial class FlatNieuw {
        public int Niw_ID { get; set; }
        public string Niw_Datum { get; set; }
        public string Niw_Titel { get; set; }
        public string Niw_Bericht { get; set; }
        public int Niw_Schooljaar { get; set; }
        public bool Niw_Publiceren { get; set; }
    }
}

我唯一的整數是來自下拉列表,因為下拉列表中的值是整數,所以這些不會失敗。 日期(基准)是一個字符串。 我對此字符串進行自定義驗證。 modelbinder綁定到此FlatNieuw對象。

我的Nieuw類具有與該類完全相同的字段名稱。 因此,當您使用UpdateModel()時,此方法仍然有效。 如果要輸入新條目,則可以使用自動映射器將此flatObject映射到普通對象。

我認為,這與phil haack的博客一起應該可以幫助您實現這一目標。 如果您有任何疑問,請隨時提出。

我遇到了同樣的問題,無法找到解決方案。 我無法相信每個人都沒有遇到這個問題。 我正在使用jquery.maskedinput.js模塊,但效果很好,但是當我開始使用“ EditorFor”添加“ [DataType(DataType.Date)]”修飾時,如果為日期時間輸入分配了class =“ text-box”類單線”。 添加此類會破壞maskedinput js。 它還將我的低日期格式設置為“ 2/3/1010”,然后將我的jquery掩碼改為“ 99/99/9999”。

根據我的經驗,對於我們正在開發的某些項目,無論是Microsoft MVC驗證還是jQuery驗證都是過分的。 這就是為什么有時候我會自己編寫/抓取小代碼的原因。

解決方案一:自定義插件(您可以將其更改為適合您的方式)

(function($) {
    $.fn.extend({
            ValidateInput: function() {
                var bValid = true;
                this.removeClass('ui-state-error');
                this.each(function() {
                    if ($(this).hasClass('date')) {

                            var valdate = checkRegexp($(this), /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2]\d{3})$/, "date format is wrong, please input as dd/MM/yyyy, e.g. 02/28/2010");
                            if (!valdate) {
                                $(this).val("input in 'dd/mm/yyyy' format");
                            }
                            bValid = bValid && valdate;
                return bValid;

                        }
                }); 

    }});

    function checkRegexp(o, regexp, n) {
        if (!(regexp.test(o.val()))) {
            o.addClass('ui-state-error');
            //updateTips(n);
            return false;
        } else {
            return true;
        }
        }

 })(jQuery);

在您看來:

  1. 在您的輸入框中添加class ='date'
  2. 調用插件$("#yourInput").alidateInput();

解決方案2:使用Jquery UI Date Pick(我現在使用的解決方案)

     <script language="javascript" type="text/javascript">
            $(function() {
// use date picker to your textbox input 
                $(".yourInput").datepicker();
                $(".yourInput").datepicker('option', { dateFormat: "dd/mm/yy" });
// disable any human input to the textbox input
                $(".yourInput").keyup(function() {
                    $(this).val("");
                });
            });
        </script>

解決方案2的詳細信息: http : //www.gregshackles.com/2010/03/templated-helpers-and-custom-model-binders-in-asp-net-mvc-2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM