小编典典

出生日期验证持续显示

c#

我在文本框中输入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

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


阅读 702

收藏
2020-05-19

共1个答案

小编典典

进行客户端验证的原因是,所jquery.validate.js使用的插件会jquery.validate.unobtrusive.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]属性不执行任何操作,可以将其删除。

2020-05-19