【问题标题】:validate date format using jqueryUI parseDate method使用 jqueryUI parseDate 方法验证日期格式
【发布时间】:2016-05-26 05:25:04
【问题描述】:

我有一个sample fiddle,我正在尝试将日期格式验证为

 $('button').click(function() {
    $('#error').text('');
    var dateParse = $.datepicker.parseDate("dd/mm/yy", $("#datepicker").val());
    if (dateParse) {
      $('#error').text(dateParse);
    } else {
      $('#error').text('invalid date format');
    }
  });

但是没有显示错误。代码有什么问题?

【问题讨论】:

    标签: jquery jquery-ui jquery-ui-datepicker


    【解决方案1】:

    错误未显示,因为parseDate() 函数中发生错误,因为日期无效。您需要先处理该错误。这里是jsFiddle

    $(function() {
      $("#datepicker").datepicker({
        dateFormat: 'dd/mm/yy',
      });
    
      $('button').click(function() {
        $('#error').text('');
        try {
        var dateParse = $.datepicker.parseDate("dd/mm/yy", $("#datepicker").val());
        } catch (e) {}
        if (dateParse) {
          $('#error').text(dateParse);
        } else {
          $('#error').text('invalid date format');
        }
      });
    });
    <link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <p>Date:
      <input type="text" id="datepicker">
    </p>
    <p id="error">
    
    </p>
    <button>
      Validate
    </button>

    我建议显示该错误而不是您的自定义:

    $(function() {
      $("#datepicker").datepicker({
        dateFormat: 'dd/mm/yy',
      });
    
      $('button').click(function() {
        $('#error').text('');
        try {
        var dateParse = $.datepicker.parseDate("dd/mm/yy", $("#datepicker").val());
        if (dateParse) {
          $('#error').text(dateParse);
        }
        } catch (e) {$('#error').text(e);}
      });
    });
    <link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <p>Date:
      <input type="text" id="datepicker">
    </p>
    <p id="error">
    
    </p>
    <button>
      Validate
    </button>

    【讨论】:

    • 宾果游戏...!我忘了try catch.. 我想要完全按照你的建议。还有一个验证,我希望它永远不会实现。月份和日期的示例交换,例如 05/07/2016,而不是 5 月 7 日的 07/05/2016 :)
    猜你喜欢
    • 2016-11-23
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    相关资源
    最近更新 更多