日期选择器验证工作不使用jQuery插件 [英] Datepicker Validation is not working on using jquery plugin

查看:133
本文介绍了日期选择器验证工作不使用jQuery插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有喜欢选择/从日期选择器中输入日期的情况。我已经使用jQuery插件日期选择器。它完美地工作。

I'm having scenario like choosing/entering of date from datepicker. I have used jquery plugin for datepicker. It worked perfectly.

正如我刚才所说,用户也有直接在搜索框中输入日期,而不是​​从日历中选择的优势。在这个阶段,因为我们都知道,用户可能会发生错误地输入日期。因此,我临危受命,jQuery的日期选择器验证插件。在那里,我发现了一些文章进行。

As I said earlier, user also having an advantage of entering date directly in textbox instead of choosing from calendar. At this stage, as we all know that the user may happen to enter the date wrongly. Hence I stepped in jquery datepicker validation plugin. There I found some articles to proceed.

的有用的链接如下所示,

The useful links are as follows,

keithwood

的jsfiddle

<一个href=\"http://stackoverflow.com/questions/13819135/jquery-date-picker-validation-problems/13819594?noredirect=1#comment48428483_13819594\">Chridam说

我试过是:

作为第一个链接说(基思木),我试图与datepicker.validation.js。但是,当我输入了错误的日期没有任何反应。下面是完整的code,我试过了,

As first link says(Keith wood), I tried with datepicker.validation.js. But nothing happens when i enter the wrong date. Below is the complete code which I tried,

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <meta charset="UTF-8">
 <title> Test for date picker</title>
 <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/south-street/jquery-ui.css"> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script> 
<script type="text/javascript" src="jquery.validate.js"></script>
<script type="text/javascript" src="jquery.ui.datepicker.validation.js"></script>
    <script src="demo.js" type="text/javascript"></script>
</head>
<body>

<form id="validateForm" action="#">
 <script >
$('#validateForm').validate({
       errorPlacement: $.datepicker.errorPlacement,
       rules: {
           validDefaultDatepicker: {
               required: true,
               dpDate: true
           },
           validBeforeDatepicker: {
               dpCompareDate: ['before', '#validAfterDatepicker']
           },
           validAfterDatepicker: {
               dpCompareDate: { after: '#validBeforeDatepicker' }
           },
           validTodayDatepicker: {
               dpCompareDate: 'ne today'
           },
           validSpecificDatepicker: {
               dpCompareDate: 'notBefore 01/01/2012'
           }
       },
       messages: {
           validFormatDatepicker: 'Please enter a valid date (yyyy-mm-dd)',
           validRangeDatepicker: 'Please enter a valid date range',
           validMultiDatepicker: 'Please enter at most three valid dates',
           validAfterDatepicker: 'Please enter a date after the previous value'
       }
   });
    </script>
 <p>
            Select Date:
           <input type="text" size="10" name="validDefaultDatepicker" id="validDefaultDatepicker"/></p>
           <script>
               $(function () {
                   $('#validDefaultDatepicker').datepicker();
               });
</script>
</form>


按照第二个链接(chridam),我型=最新概念试图直接。这给了我希望,因为它的工作完美。虽然该解决方案是好的,它不工作的IE浏览器。下面是完整的code,

As per the second link(chridam), I tried with type = date concept directly. It gave me hope as it worked perfectly. Though the solution is nice, it is not working IE browsers. Below is the complete code,

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
 <script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
  <script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
  <script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>

<script type="text/javascript">
$(function () {

    $("#jQueryValidateTest").validate();

    $("[type=date]").datepicker({
        onClose: function () {
            $(this).valid();
        }
    });
});
</script>
<style>
    .valid {
  background: green;
  color: #fff;
}
.error {
 background: red;
  color: #fff;
}
</style>  
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
    <form id="jQueryValidateTest">
<input type="date" required>
</form>​
</td>
</tr>
</table>
</body>
</html>    

希望我没有混淆你。请帮我克服这一障碍。先谢谢了。

Hope I'm not confusing you. Kindly help me to overcome this hurdle. Thanks in advance.

推荐答案

如果我理解你的问题,你完全想有日期的定制输入验证。这是一个问题,我最近有一个航班预订网站(现场前。

If I understand your question completely you'd like to have custom input validation for dates. It's a problem I recently had for a flight booking website (live ex.)

有一点肯定是类型的输入域日期都不错,但不是非常的X浏览器,因为他们推出了与他们自己的日期格式,这取决于设备/操作系统/浏览器文化。所以我的解决办法是为文本输入类型。它还使用jQuery UI的日期选择器和不引人注目的验证插件。

One thing for sure is that input fields of type date are nice, but not very x-browser because they roll out with they're own date format, depending on the device/OS/browser culture. So my solution is for text input types. It also uses jquery UI datepicker and unobtrusive validation plugin.

要克服这一障碍的一大优点是jQuery UI的日期选择器内部,除了缺少手动输入验证,是期权的 constrainInput 它通过它只允许的字符是当前格式。这已经是一个巨大的胜利!

To conquer this hurdle one big advantage that IS inside jQuery UI datepicker, apart from the missing manual input validation, is the option constrainInput which allows only the characters by it's current format. That's already a big win!

在第二记jQuery用户界面还带有文化文件实例datepickers对自定义格式。

On a second note jQuery UI also comes with culture files to instantiate datepickers against a custom format.

这是最重要的是建筑,我相信需要自定义验证方法。
后来有很大的区别相比,您的设置可能是使用 MINDATE &安培; MAXDATE 选项。不知道这是适用于你,但是这就是我得到了它的正确验证。

Building on top of that, I believe a custom validation method is required. Then one big difference compared to your setup might be the use of minDate & maxDate options. Not sure if that's applicable to you but that's how I got it to validate correctly.

/**
 * @description resolves an issue with chrome & safari date validation
 * @param {String} format : regional dateformat
 */
setValidator: function (format) {
    var self = this, // scope
        settings = this.settings, // object literal
        data = settings.data, // mapping for data-attributes
        options = settings.options; // my custom behavior options

    $.validator.addMethod('date', function (value, element) {
        var inst, // jquery ui datepicker data inst object => very handy
            parts, // split the user input
            minDate = new Date(), // create a min range
            maxDate = new Date(minDate), // create a max range
            newDate; // the date to be validated in the end

        // unrequired fields
        if (this.optional(element)) {
            return true;
        }

        try {
            // get the data instance from the element, put there by jquery-ui
            // warning: inline datepickers have their instance on the resp. div
            inst = options.isInline ? self.findDatepicker($(element)).data(data.datepicker) : $(element).data(data.datepicker);

            // determine the epoch timestamps of the input, based on the options minDate and maxDate, for calculation
            minDate = typeof inst.settings.minDate === 'object' ? inst.settings.minDate.getTime() : minDate.setDate(minDate.getDate() + parseInt(inst.settings.minDate.replace(/[+d]/g, ''), 10));
            maxDate = maxDate.setDate(maxDate.getDate() + parseInt(inst.settings.maxDate.replace(/[+d]/g, ''), 10));

            // correct months 0-based
            // correct 2digit years
            // add hours to the maxDate
            parts = value.split('/');
            if (parts.length === 3) {
                parts[0] = parseInt(parts[0], 10);
                parts[1] = parseInt(parts[1], 10) - 1;
                parts[2] = parseInt(parts[2], 10) < 100 ? parseInt(parts[2], 10) + 2000 : parseInt(parts[2], 10);
                // notice how I switch the parts against the default format
                newDate = new Date(parts[2], parts[1], parts[0], 23, 59, 59, 0).getTime();
                if ($(element).data(data.maxdate)) {
                    newDate = newDate - (new Date(newDate).getHours() * 60 * 60 * 1000);
                }

                // unfortunately not very usefull as it doesn't return anything when false => value.split('/')
                //$.datepicker.parseDate(format, value);
            } else {
                newDate = 0;
            }

            return newDate >= minDate && newDate <= maxDate;
        }
        catch (err) {
            console.log(err);
        }
    });
}

基本上,我遍历每个jQuery的日期选择器:

Basically I loop over every jQuery datepicker:


  • 获取/设置从国际化的文化档案文化与阿贾克斯=> /脚本/ lib中/ jQuery的的UI / UI /国际化/日期选择器 - {{文​​化}} JS

  • 设置的格式参数=> self.setValidator(regional.dateFormat)的验证;

  • 设置的选项日期选择器=> $('。日期选择器)日期选择器(选件);

  • get/set the culture from i18n culture files with ajax => '/scripts/lib/jquery-ui/ui/i18n/datepicker-{{culture}}.js'
  • set the validator with the format param => self.setValidator(regional.dateFormat);
  • set the options for datepicker => $('.datepicker').datepicker(options);

希望是有道理的一点,或者至少把你在正确的方向。
如果有任何不明白,问了......因为我知道这是不是一个复制/粘贴的解决方案^^

Hope that makes sense a bit or at least push you in the right direction. If something is unclear, ask away ... as I realize this is not a copy/paste solution ^^

这篇关于日期选择器验证工作不使用jQuery插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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