简体   繁体   English

使用ComponentModel.DataAnnotations进行MVC3验证的英国日期格式(也使用jquery ui datepicker)

[英]MVC3 Validation with ComponentModel.DataAnnotations for UK date format (also using jquery ui datepicker)

I see there are some similar questions to this, but none solve my issue. 我看到有一些类似的问题,但没有一个能解决我的问题。

I am working on an MVC3 app with Entity Framework 4.3. 我正在使用Entity Framework 4.3开发MVC3应用程序。 I have a UK date field that i plan to allow the user to edit using the Jquery UI datepicker (which i got working thanks to this blog ). 我有一个英国日期字段,我计划允许用户使用Jquery UI datepicker进行编辑(由于这个博客我得到了工作)。

Fortunately for me this blog includes instructions on making the datepicker using UK format, however, the EF validation is still telling me that i need to enter a valid date format. 幸运的是,这个博客包含了使用英国格式制作日期选择器的说明,但是,EF验证仍然告诉我需要输入有效的日期格式。 Wierdly it doesn't prevent me from submitting the date to the DB its just the unobtrusive validation kicking in and displaying the message. 很奇怪,它并没有阻止我将日期提交给数据库,只是不显眼的验证开始并显示消息。

At the moment I have the following data annotation: 目前我有以下数据注释:

[DataType(DataType.Date)]
public System.DateTime Module_Date { get; set; }

but i have also tried adding: 但我也试过添加:

[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]

which had no effect at all. 这完全没有效果。 I hope some one has a solution because i don't fancy turning off the unobtrusive validation to stop this error message. 我希望有人有一个解决方案,因为我不喜欢关闭不引人注意的验证来停止此错误消息。

Thanks 谢谢

EDIT 编辑

following @Iridio answer, i looked into adding a Model Binding, and indeed from the few posts like this one that i read it seemed to be the right thing to do, but what i have come up with has no effect. 在@Iridio回答之后,我考虑添加一个模型绑定,实际上从像我这样读过它的几个帖子似乎是正确的做法,但我想出的并没有效果。 here is what i have tried: 这是我尝试过的:

public class DateTimeBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);

        return date;
    }
}

with this in the Application_Start() method of the Global.asax.cs file: Global.asax.cs文件的Application_Start()方法中使用它:

ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder());

Right, the problem was with the jquery validate scripts insisting on using the US datefomat. 是的,问题在于jquery验证脚本坚持使用US datefomat。 I will restrain my self from going on a proper rant about the fact that the majority of the world uses dd/mm/yyyy though. 我将限制自己对世界大多数人使用dd / mm / yyyy这一事实进行适当的咆哮。

Anyway, eventually i found the answer to my woes in a comment to an answer of a similar question , the author of which kindly wrote a blog post about how he solved the issue. 无论如何,最终我在一个类似问题的答案的评论中找到了我的困境的答案,作者亲切地写了一篇关于他如何解决这个问题的博客文章

Basically I have used the jquery globalize script and just set the culture to en-GB . 基本上我使用了jquery globalize脚本 ,只是将文化设置为en-GB I should mention that in his blog he doesn't mention where to put the bit where you specify the culture, so i just shoved in in script tags in the page under the references to the globalization scripts: 我应该提一下,在他的博客中他没有提到把你指定文化的位置放在哪里,所以我只是在全球化脚本的引用下的页面中的脚本标签中插入:

<script src="@Url.Content("~/Scripts/globalize.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/globalize.culture.en-GB.js")" type="text/javascript"></script>
<script type="text/javascript">
    Globalize.culture("en-GB");
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || Globalize.parseDate(value);
    };
</script>

You have to write you own ModelBinder for the DateTime type. 您必须为DateTime类型编写自己的ModelBinder。

This is a binder that I wrote for a similar problme but with Decimal type (maybe you will need it). 这是我为类似的问题写的一个活页夹,但是使用Decimal类型(也许你需要它)。 you should grasp the idea and adapt it to your need 你应该掌握这个想法,并根据你的需要进行调整

public class DecimalModelBinder : IModelBinder
{
  public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
  {
    ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    ModelState modelState = new ModelState { Value = valueResult };
    object actualValue = null;
    try
    {
      actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
    }
    catch (FormatException e)
    {
      modelState.Errors.Add(e);
    }

    bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
    return actualValue;
  }
}

Then in global.asax you register your binder and you're done 然后在global.asax中注册你的活页夹,你就完成了

protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();
  RegisterGlobalFilters(GlobalFilters.Filters);
  RegisterRoutes(RouteTable.Routes);
  //Here you tell how to hendle the specific type 
  ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
}

UPDATE UPDATE

After your clarification this answer should help 澄清后, 这个答案应该有所帮助

I believe there is a bug in the script version of the jquery ui datepicker that ships with the mvc3 framework (jquery-ui-1.8.11.js). 我相信jvery ui datepicker的脚本版本中有一个错误,该错误随mvc3框架(jquery-ui-1.8.11.js)一起提供。

If you specify the date in the uk format (as indeed the blog states): 如果您以英国格式指定日期(实际上是博客说明):

$(document).ready(function () {
    $('.date').datepicker({dateFormat: "dd/mm/yy"});
});

then jquery-ui-1.8.11.js seems to have an issue with validating the date and keeps asking for a valid uk date (but the validation appears random). 那么jquery-ui-1.8.11.js似乎在验证日期方面存在问题,并且一直要求提供有效的英国日期(但验证似乎是随机的)。 If you change the date format to "mm/dd/yy" then this issue will go away but thats no good for uk dates. 如果您将日期格式更改为“mm / dd / yy”,那么此问题将会消失,但这对英国日期没有好处。

The issue has been resolved in a later version of that library so download the latest version (I believe 1.8.18 at time of writing) or reference the cdn: 该问题已在该库的更高版本中得到解决,因此请下载最新版本(我相信在撰写本文时为1.8.18)或引用该cdn:

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js" type="text/javascript"></script>

Actually I have found a better solution here.... by #fretje 实际上我在这里找到了一个更好的解决方案...... #fretje

Override jquery date 覆盖jquery日期

I have modified his/her code slightly though so that it can still take date formats like 30 May 2012 below. 我稍微修改了他/她的代码,以便它仍然可以采用如下的2012年5月30日的日期格式。

$(function () {
    $.validator.addMethod(
        "date",
        function (value, element) {

            //Added to validate dates like 31 May 2012
            if (value.split('/').length === 1) 
                return this.optional(element) || !/Invalid|NaN/.test(new Date(value));

            var bits = value.match(/([0-9]+)/gi), str;
            if (!bits)
                return this.optional(element) || false;
            str = bits[1] + '/' + bits[0] + '/' + bits[2];
            return this.optional(element) || !/Invalid|NaN/.test(new Date(str));
        },
        "Please enter a date in the format dd/mm/yyyy"
    );

    $global.init();
});

I've had this problem just now, took me hours to track down the reason. 我刚刚遇到这个问题,花了我几个小时来追查原因。 I'm not saying this is your issue but after having spent hours switching globalisations on everything, etc. i thought I'd post the issue on here for any people struggling like me. 我不是说这是你的问题,而是在花了几个小时来切换所有事情的全球化等等之后,我想我会在这里发布问题,让任何像我一样苦苦挣扎的人。

Anyway, the problem in my project was actually not what i thought it was. 无论如何,我的项目中的问题实际上并不是我认为的那样。 I had decorated the property with [DataAnnotationsExtentions.Date] which, it turns out, mucks up the client side validation in chrome when it comes to the localisation (ie if you want a day after the 12th in England) although it seems to work fine in other browsers. 我用[DataAnnotationsExtentions.Date]装饰了这个属性,事实证明,当涉及到本地化时(即如果你想要在英格兰的第12天之后的一天),它会破坏Chrome中的客户端验证,尽管它似乎工作正常在其他浏览器中。 As soon as I removed that it worked 一旦我删除它,它工作

The problem is that by some reason if you put a class called "date" in your textbox, Chrome just get crazy as discribed here at this blog . 问题在于,如果你在文本框中放入一个名为“日期”的课程,Chrome就会变得疯狂,就像在这个博客中所描述的那样 I had the same problem and I just changed the class name to customDate and it was solved. 我有同样的问题,我只是将类名更改为customDate,它已解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET MVC 2和ComponentModel.DataAnnotations验证:最小值属性 - ASP.NET MVC 2 and ComponentModel.DataAnnotations Validation: minimum value attribute 控制器未收到英国格式的MVC3日期 - MVC3 Date in UK Format not received on Controller 使用System.ComponentModel.DataAnnotations的验证摘要; - Validation Summary using System.ComponentModel.DataAnnotations; ASP.NET MVC3 System.ComponentModel.DataAnnotations和Association - ASP.NET MVC3 System.ComponentModel.DataAnnotations and Association 表单验证System.ComponentModel.DataAnnotations和JQuery提交 - Forms validation System.ComponentModel.DataAnnotations and JQuery submit 正常表达日期不起作用; MVC3 DataAnnotations - Regular expression for date not working; MVC3 DataAnnotations 使用DataAnnotations的DateTime / Date的MVC2客户端/服务器验证 - MVC2 client/server validation of DateTime/Date using DataAnnotations ASP.NET MVC3 System.ComponentModel.DataAnnotations——注释能否确定它正在验证的类? - ASP.NET MVC3 System.ComponentModel.DataAnnotations -- can an annotation determine the class it is validating? WPF DatePicker美国和英国日期格式问题 - WPF DatePicker US AND UK date format issue MVC3非侵入式验证不适用于自定义DataAnnotations属性 - MVC3 Unobtrusive Validation not working for custom DataAnnotations attribute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM