出生日期验证一直显示 [英] Date of Birth validation keeps showing

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

问题描述

我正在我的文本框中输入 DOB - 22/12/1986 并且验证一直在触发.它说:

字段 DOB 必须是日期.

我的模型:

[System.ComponentModel.DisplayName("DOB")][DisplayFormat(DataFormatString = "@{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)][必填(ErrorMessage =需要出生日期")][RegularExpression(@"{0:dd/MM/yyyy}", ErrorMessage = "Invalid Date")]//下面是一个链接公共日期时间 DOB { 获取;放;}

我的查看:

@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" })

MS SQL 数据库中的字段是:DateTime

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

解决方案

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

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

日期:函数(值,元素){返回 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"格式

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

I am typing a DOB - 22/12/1986 into my text box and the validation keeps firing. It says:

The field DOB must be a date.

My MODEL:

[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; }

My VIEW:

<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>

In MS SQL database the field is: DateTime

Why does my validation say that the date i type in is invalid?

解决方案

The reason for the client side validation is that the jquery.validate.js plugin used by jquery.validate.unobtrusive.js validates dates based on MM/dd/yyyy format and your entering dates based on a dd/MM/yyyy format.

The specific code used in jquery.validate.js for validation is

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

which depending on the browser your using will give different results (in Chrome, new Date('22/12/1986') returns Invalid Date but in FireFox it returns 1987-10-11T13:30:00.000Zwhich is valid, just not the date you entered)

You need to override the $.validator to format dates in your culture. One option is to use the jquery.globalize plugin.

Alternatively you can write your own script. Note that the following script is taken from my own plugin used in conjunction with a @Html.DatePickerFor() extension method that generates a datepicker. The extension method adds html attributes for the date format based on the server culture and is read with the var format = regex.exec(this.inputFormat); line of code that I have commented out and replaced with your hard coded format. If you only ever want the dd/MM/yyyy format, then the script can be simplified because you only need the 'little-endian' format

<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>

Side note: Your [RegularExpression] attribute does nothing and can be removed.

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

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