How to validate date type field by using jquery validation

只谈情不闲聊 提交于 2021-01-29 22:30:02

问题


I am using ASP.NET MVC. I have a problem with calender - date validation.

The codes for this calendar are in the following :

<script>
    $(function () {
        $(".date").datepicker({ dateFormat: 'dd.mm.yy' }).
    });
</script>

<tr>
 <td style="text-align:left; padding-left:50px;">
     @Html.TextBoxFor(model => model.startdate, "{0:dd.MM.yyyy}",        
             new { @class = "date", style = "width:65px; font-weight: bold;", @readonly = "true" })
 </td>
</tr>

I validate the fields of the form by JQuery validation plugin. For this, I included the following two JavaScript libraries;

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

After I added the JavaScript libraries above, the date field can not pass validation and does not work properly.

For example, i have a date like: 19.09.2014.

The day part of the calendar (19) behaves as a month, and the month part of the calendar (09) behaves as day.

How can i solve this problem? I want to get validated date fields and month-day parts of the calender works properly.

Any help will be appreciated.


回答1:


Below code do 2 things 1)Set date formatand 2)Date format Validation

$(function () {
        $.validator.addMethod('date',
        function (value, element) {
            if (this.optional(element)) {
                return true;
            }
            var valid = true;
            try {
                $.datepicker.parseDate('dd.mm.yy', value);
            }
            catch (err) {
                valid = false;
            }
            return valid;
        });
        $(".datetype").datepicker({ dateFormat: 'dd.mm.yy' });
    });

Add [DataType(DataType.Date)]for validation in your model.



来源:https://stackoverflow.com/questions/25934295/how-to-validate-date-type-field-by-using-jquery-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!