日期验证 MVC 错误 [英] Error in date validation MVC

查看:18
本文介绍了日期验证 MVC 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型类属性如下

   public DateTime PurchaseDate { get; set; }

和内部视图

 @Html.TextBoxFor(model => model.PurchaseDate, new { @class = "form-control date-picker" })
 @Html.ValidationMessageFor(model => model.PurchaseDate)

我在表格中给出这样的日期

and I am giving a date like this in form

19/06/2015

但是它给出了验证消息并且不允许提交页面,消息是这样的

But it gives validation message and not allows page to be submitted, message is like this

The field PurchaseDate must be a date.

如果我以 mm/dd/yyyy 格式给出日期,它会起作用.谁能指出我在这里做错了什么?

if I give date in mm/dd/yyyy format it works. Can anyone point out what I am doing wrong here?

推荐答案

发生客户端错误是因为默认情况下 jquery.validate 使用 MM/dd/yyyy 格式.您可以覆盖 $.validator.addMethod('date', function (value, element) 函数来测试该值是否在您期望的 dd/MM/yyyy 中. 请注意,以下代码来自我自己的 jquery 插件,该插件与 @Html.DatePickerFor() 辅助方法相关联,该方法根据服务器在输出中呈现 data-dateformat 属性文化,所以它可能对你的需求来说太过分了

The client side error is occurring because by default jquery.validate tests the value using the MM/dd/yyyy format. You can override the $.validator.addMethod('date', function (value, element) function to test that the value is in the dd/MM/yyyy you expect. Note the following code is from my own jquery plugin associated with a @Html.DatePickerFor() helper method which renders a data-dateformat attribute in the output based on the servers culture, so it may be an overkill for your needs

添加以下脚本(不是document.ready中,而是在jquery.validate.unobtrusive之后)

Add the following scripts (not in document.ready, but after jquery.validate.unobtrusive)

Date.prototype.isValid = function () {
  return !isNaN(this.getTime());
}

globalDate = function (value, formatString) {
  // Initialise a new date
  var date = new Date(0);
  if (value == undefined) {
    // Return todays date
    return date;
  }
  // Get the components of the format
  // The separator can be forward slash, hyphen, dot and/or space
  var regex = new RegExp(/([dMy]+)([s/.-]+)([dMy]+)([s/.-]+)([dMy]+)/);
  //var format = regex.exec(this.inputFormat);
  var format = regex.exec(formatString);
  // Get the components of the value
  regex = new RegExp(/(d+)([s/.-]+)(d+)([s/.-]+)(d+)/);
  value = regex.exec(value);
  // Check the value is valid
  if (value === null || value[2] !== format[2] || value[4] !== format[4]) {
    // Its not valid
    date.setTime(Number.NaN);
    return date;
  }
  // TODO: What if year entered as 2 digits?
  var day = Number.NaN;
  var month = Number.NaN;
  var year = Number.NAN;
  if (format[1].charAt(0) === 'd') {
    // little-endian (day, month, year)
    day = parseInt(value[1]);
    month = parseInt(value[3]) - 1;
    year = parseInt(value[5]);
  } else if (format[1].charAt(0) === 'M') {
    // middle-endian (month, day, year)
    day = parseInt(value[3]);
    month = parseInt(value[1]) - 1;
    year = parseInt(value[5]);
  } else {
    // big endian (year, month, day)
    day = parseInt(value[5]);
    month = parseInt(value[3]) - 1;
    year = parseInt(value[1]);
  }
  date.setFullYear(year);
  date.setMonth(month);
  date.setDate(day);
  // Check its valid
  if (date.getDate() !== day || date.getMonth() !== month || date.getFullYear() !== year) {
    date.setTime(Number.NaN);
    return date;
  }
  return date;
}

$.validator.addMethod('date', function (value, element) { 
  var format = "dd/MM/yyyy";
  return this.optional(element) || globalDate(value, format).isValid();
}

如果您只想测试格式dd/MM/yyyy,那么您可以通过使用

If you only ever want to test for the format dd/MM/yyyy, then you could simplify the globalDate() function by just using

var date = new Date();
date.setHours(0, 0, 0, 0);
var components = value.split('/');
var day = components[0];
var month = components[1];
var year = components[2];
date.setFullYear(year);
....

编辑

除了 OP 关于服务器端验证失败的评论之外,服务器文化需要接受格式为 dd/MM/yyyy 的日期字符串.在 web.config.cs 文件

Further to OP's comments regarding server side validation failing, the server culture needs to accept a date string in the format dd/MM/yyyy. In the web.config.cs file

<system.web>
  <globalization culture="en-AU" uiCulture="en-AU"/> // adjust to your culture code
  ....

这篇关于日期验证 MVC 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆