【问题标题】:Date of Birth validation keeps showing出生日期验证一直显示
【发布时间】:2016-09-24 13:44:48
【问题描述】:

我在我的文本框中输入 DOB - 22/12/1986 并且验证不断触发。它说:

The field DOB must be a date.

我的模型

[System.ComponentModel.DisplayName("DOB")]
[DisplayFormat(DataFormatString = "@{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Date Of Birth is required")]
[RegularExpression(@"{0:dd/MM/yyyy}", ErrorMessage = "Invalid Date")] // below is a link
public DateTime DOB { get; set; }

我的视图

<div class="form-group">
    @Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.DOB, "", new { @class = "text-danger" })
    </div>
</div>

MS SQL database 中的字段是:DateTime

为什么我的验证显示我输入的日期无效?

【问题讨论】:

  • 你的正则表达式...它不是一个有效的正则表达式(或者更确切地说只会匹配你输入的文字字符串),我认为你在 DisplayFormatAttribute 的引号的错误一侧有 @ /跨度>

标签: c# jquery asp.net-mvc razor model-view-controller


【解决方案1】:

客户端验证的原因是jquery.validate.unobtrusive.js 使用的jquery.validate.js 插件基于MM/dd/yyyy 格式验证日期,而您输入的日期基于dd/MM/yyyy 格式。

jquery.validate.js中用于验证的具体代码是

date: function(value, element) {
    return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}

这取决于您使用的浏览器会给出不同的结果(在 Chrome 中,new Date('22/12/1986') 返回 Invalid Date,但在 FireFox 中返回 1987-10-11T13:30:00.000Z这是有效的,只是不是您输入的日期)

您需要覆盖 $.validator 以格式化您的文化中的日期。一种选择是使用jquery.globalize 插件。

您也可以编写自己的脚本。请注意,以下脚本取自我自己的插件,该插件与生成日期选择器的@Html.DatePickerFor() 扩展方法结合使用。扩展方法为基于服务器文化的日期格式添加 html 属性,并使用 var format = regex.exec(this.inputFormat); 代码行读取,我已将其注释掉并替换为您的硬编码格式。如果您只需要 dd/MM/yyyy 格式,那么可以简化脚本,因为您只需要 'little-endian' 格式

<script type="text/javascript">
    // Override default date validator format to allow culture specific format
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || globalDate(value).isValid();
    };

    globalDate = function (value) {
        // 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]+)/);
//------------- see notes above
        //var format = regex.exec(this.inputFormat);
        var format = regex.exec('dd/MM/yyyy');
//------------- 
        // 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;
    }

    // Methods 
    Date.prototype.isValid = function () {
        return !isNaN(this.getTime());
    }
</script>

附注:您的 [RegularExpression] 属性什么都不做,可以删除。

【讨论】:

    【解决方案2】:

    在 Ganesh 提到的两个地方将 . 替换为 / - DisplayFormat 属性和 RegularExpression 属性。

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多