bootstrap验证日期DD.MM.YYYY jquery

时间:2022-04-23 11:57:51

I want to validate my first field on the form createViewModal, datepickerCreateModal in dd.mm.yyyy format. I was searching for some regex and I found it:

我想以dd.mm.yyyy格式在createViewModal,datepickerCreateModal表单上验证我的第一个字段。我正在寻找一些正则表达式,我找到了它:

/(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d/

But it seems that this regEX is not quite good - it pulls just two digits from a year ("20" instead of "2016")

但似乎这个regEX并不是很好 - 它从一年(“20”而不是“2016”)拉出两位数

Can you write me a full regex for dd.mm.yyyy (11.05.2016)? I think I will be able to create callback function with this regex through bootstrap validator.

你能为dd.mm.yyyy(11.05.2016)写一个完整的正则表达式吗?我想我将能够通过bootstrap验证器使用此正则表达式创建回调函数。

If someone already has this regex or a similar solution, I would be happy to hear it!

如果有人已经有这个正则表达式或类似的解决方案,我会很高兴听到它!

<div class="modal fade" id="createViewModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
        <span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">New SAR</h4>
      </div>
      <div class="modal-body">
        <div id="formregister">
          <form action="" class="form-horizontal" role="form" id="createViewModal">
            <p class="qc-errmsg" style="display: none;">&nbsp;</p>
            <div class="form-group">
              <label for="Date" class="col-sm-2 control-label">Date</label>
              <div class="col-sm-10">
                <input type="text" class="form-control" id="datepickerCreateModal" name="Date" placeholder="Date">
              </div>
            </div>
            <div class="form-group">
              <label for="Client" class="col-sm-2 control-label">Client</label>
              <div class="col-sm-10">
                @Html.DropDownList("Client1", (SelectList)ViewBag.ClientID, "", new { @class = "form-control", tabindex = "1", id = "client" })
              </div>
            </div>
            <div class="form-group">
              <label for="EventType" class="col-sm-2 control-label">Event Type</label>
              <div class="col-sm-10">
                @Html.DropDownList("Eventtype", (SelectList)ViewBag.EventTypeID, "", new { @class = "form-control", tabindex = "2", id = "event" })
              </div>
            </div>
            <div class="form-group">
              <div class="col-sm-offset-2 col-sm-10">
                <button type="button" class="close1 btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" value="cart" class="btn btn-primary">Save Changes</button>
              </div>
            </div>
          </form>
        </div>
        <!-- form register -->
        <div id="successfulpost" style="font: bold 12px Verdana, Arial, Helvetica, sans-serif; color: #ff0000; display: none;">
          <p class="jst-txt">
            <span>Thank you,</span> for showing your Interest !!
          </p>
          <p class="jst-txt">Our property advisor shall get in touch with you very shortly..</p>
        </div>
      </div>
      <!-- model body-->
    </div>
  </div>
</div>
<script>
  $(function () {
      $('#createViewModal').bind('show', function () {
          $("#datepickerCreateModal").val($(this).val() + ".");
      });
  });
  function clearCreateModal() {
      $('#event').val(0);
      $('#client').val(0);
      $('#datepickerCreateModal').val("");
      $('#datepickerCreateModal').focus();
  }
  $('.close,.close1').click(function () {
      $('#client').val(0);
      $('#event').val(0);
      $('#datepickerCreateModal').val('');
      $('#createViewModal').data('bootstrapValidator').resetForm();
  });
  $('#dateFrom, #dateTo,#datepickerCreateModal,#datepickerEditModal').datepicker({
      todayBtn: "linked",
      daysOfWeekHighlighted: "0,6",
      calendarWeeks: true,
      autoclose: true,
      format: "dd.mm.yyyy"
  });
  $.fn.dataTable.ext.search.push(
      function (settings, data, dataIndex) {
          var minDate = $('#datepicker10').val();
          var maxDate = $('#datepicker11').val();
          var ageInputs = data[1].split('.');
          var age = new Date(ageInputs[2], ageInputs[1] - 1, ageInputs[0]);
          //var getdate = date.getDate();
          var min;
          if (minDate.indexOf(".") > -1) {
              var input = minDate.split('.');
              var count = input.length;
              if (count > 2) {
                  min = new Date(input[2], input[1] - 1, input[0]);
              }
          }
          var max = new Date(maxDate.split('.')[2], maxDate.split('.')[1] - 1, maxDate.split('.')[0]);
          if ((isNaN(min) && isNaN(max)) ||
          (isNaN(min) && age <= max) ||
          (min <= age && isNaN(max)) ||
          (min <= age && age <= max)) {
              return true;
          }
          return false;
      }
  );
  var t;
  $(document).ready(function () {
      'use strict';
      $('#createViewModal').bootstrapValidator({
          // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
          feedbackIcons: {
              valid: 'glyphicon glyphicon-ok',
              invalid: 'glyphicon glyphicon-remove',
              validating: 'glyphicon glyphicon-refresh'
          },
          fields: {
              Date: {
                  message: 'Date is not valid',
                  validators: {
                      notEmpty: {
                          message: 'Date  is required and cannot be empty'
                          //},
                          //stringLength: {
                          //    min: 6,
                          //    max: 30,
                          //    message: 'The Album Name  must be more than 6 and less than 30 characters long'
                          //},
                          //regexp: {
                          //    regexp: /(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d/,
                          //    message: 'The Album Name  can only consist of alphabetical and number'
                      }

                  }

                  //form.submit();
              },
              Client1: {
                  message: 'Client is not valid',
                  validators: {
                      notEmpty: {
                          message: 'Client  is required and cannot be empty'
                      }
                  }
              },
              Eventtype: {
                  message: 'Event type is not valid',
                  validators: {
                      notEmpty: {
                          message: 'Event type  is required and cannot be empty'
                      }
                  }
              }

          }
      }).on('success.form.bv', function (e) {
          // Prevent form submission
          //$('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
          $('#createViewModal').data('bootstrapValidator').resetForm();

          // Prevent form submission
          e.preventDefault();

          // Get the form instance
          var $form = $(e.target);

          // Get the BootstrapValidator instance
          var bv = $form.data('bootstrapValidator');

          // Use Ajax to submit form data
          $.post($form.attr('action'), $form.serialize(), function (result) {
              console.log(result);
          }, 'json');

          $.ajax({... });
          // Do whatever you want here ...
      });
      t = $('#example').DataTable({
          "iDisplayLength": 1000,
          //dom: 'Bfrtip',
          buttons: [
              'copy', 'csv', 'excel', 'pdf', 'print'
          ],
          "columnDefs": [
              {
                  "targets": [0],
                  "visible": false,
                  "searchable": false
              },
              { "width": "200px", "targets": 6 }
          ]
      });
      yadcf.init(t,
          [
              {
                  column_number: 0,
                  filter_type: "multi_select",
                  select_type: 'select2'
              },
              {
                  column_number: 3,
                  filter_type: "multi_select",
                  select_type: 'chosen'
              },
              {
                  column_number: 4,
                  filter_type: "multi_select",
                  select_type: 'chosen'
              }
          ]
      );
  });
</script>

3 个解决方案

#1


7  

First try is always \d\d\.\d\d\.\d\d\d\d.

首先尝试总是\ d \ d \。\ d \ d \。\ d \ d \ d \ d。

It's too wide, obviously. Let's polish it.

显然,它太宽了。让我们擦亮它。

^(0[1-9]|[12]\d|3[01])\.(0[1-9]|1[012])\.((?:19|20)\d\d)$

^(0 [1-9] | [12] \ d | 3 [01])\(0 [1-9] | 1 [012])。\。((?: 19 | 20)\ d \ d) $

It still has false positives with like 31.02.1999 dates

它仍有误报,如31.02.1999日期

#2


7  

The reason it pulls just the first two digits of the year is that they are the only ones in the third capturing group. To fix that, you can just include the remaining two digits in the enclosing third ():

它只拉出一年中前两位数的原因是它们是第三个捕获组中唯一的数字。要解决这个问题,您可以在封闭的third()中包含剩余的两位数字:

(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d
                                           ^     ^
(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19\d\d|20\d\d)
                                           ^             ^

See it in action

看到它在行动

Mystery solved.

谜团已揭开。


With that said, if you want perfect validation with different days per month, leap years and what not, let me offer you a slight variation on a previous answer of mine. Ready?

话虽如此,如果你想要每月不同的日子,闰年以及不同的日子进行完美的验证,那么让我在之前的答案中给你一点点变化。准备?

((?:0[1-9]|[12]\d|3[01])(?=\.(?:0[13578]|1[02]))|(?:0[1-9]|[12]\d|30)(?=\.(?:0[469]|11))|(?:0[1-9]|1\d|2[0-8]|29(?=\.\d{2}\.\d*(?:(?:(?!\d{2}00)(?=\d{2}(?:[13579][26]|[02468][048])))|(?=(?:[13579][26]|[02468][048])00))\d{4}(?!\d)))(?=\.02))\.(\d{2})\.(\d{4,})

Experiment yourself

实验自己

Ah, the humanity!

啊,人性!

Long story short - yea, it is indeed complex. Read the original answer if you want more insight.

长话短说 - 是的,确实很复杂。如果您想要更深入的了解,请阅读原始答案。


Alternatively, you could use the way shorter (but still cumbersome) regex that validates correctly everything, except for leap years:

或者,您可以使用更短(但仍然繁琐)的正则表达式来正确验证所有内容,除了闰年:

((?:0[1-9]|[12]\d|3[01])(?=\.(?:0[13578]|1[02]))|(?:0[1-9]|[12]\d|30)(?=\.(?:0[469]|11))|(?:0[1-9]|1\d|2[0-9])(?=\.02))\.(\d{2})\.(\d{4,})

Experiment yourself

实验自己

#3


4  

Try to use this regex:

尝试使用此正则表达式:

It works for me

这个对我有用

^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

if you are using textbox then try to use jQuery masking

如果您使用的是文本框,请尝试使用jQuery掩码

#1


7  

First try is always \d\d\.\d\d\.\d\d\d\d.

首先尝试总是\ d \ d \。\ d \ d \。\ d \ d \ d \ d。

It's too wide, obviously. Let's polish it.

显然,它太宽了。让我们擦亮它。

^(0[1-9]|[12]\d|3[01])\.(0[1-9]|1[012])\.((?:19|20)\d\d)$

^(0 [1-9] | [12] \ d | 3 [01])\(0 [1-9] | 1 [012])。\。((?: 19 | 20)\ d \ d) $

It still has false positives with like 31.02.1999 dates

它仍有误报,如31.02.1999日期

#2


7  

The reason it pulls just the first two digits of the year is that they are the only ones in the third capturing group. To fix that, you can just include the remaining two digits in the enclosing third ():

它只拉出一年中前两位数的原因是它们是第三个捕获组中唯一的数字。要解决这个问题,您可以在封闭的third()中包含剩余的两位数字:

(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d
                                           ^     ^
(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19\d\d|20\d\d)
                                           ^             ^

See it in action

看到它在行动

Mystery solved.

谜团已揭开。


With that said, if you want perfect validation with different days per month, leap years and what not, let me offer you a slight variation on a previous answer of mine. Ready?

话虽如此,如果你想要每月不同的日子,闰年以及不同的日子进行完美的验证,那么让我在之前的答案中给你一点点变化。准备?

((?:0[1-9]|[12]\d|3[01])(?=\.(?:0[13578]|1[02]))|(?:0[1-9]|[12]\d|30)(?=\.(?:0[469]|11))|(?:0[1-9]|1\d|2[0-8]|29(?=\.\d{2}\.\d*(?:(?:(?!\d{2}00)(?=\d{2}(?:[13579][26]|[02468][048])))|(?=(?:[13579][26]|[02468][048])00))\d{4}(?!\d)))(?=\.02))\.(\d{2})\.(\d{4,})

Experiment yourself

实验自己

Ah, the humanity!

啊,人性!

Long story short - yea, it is indeed complex. Read the original answer if you want more insight.

长话短说 - 是的,确实很复杂。如果您想要更深入的了解,请阅读原始答案。


Alternatively, you could use the way shorter (but still cumbersome) regex that validates correctly everything, except for leap years:

或者,您可以使用更短(但仍然繁琐)的正则表达式来正确验证所有内容,除了闰年:

((?:0[1-9]|[12]\d|3[01])(?=\.(?:0[13578]|1[02]))|(?:0[1-9]|[12]\d|30)(?=\.(?:0[469]|11))|(?:0[1-9]|1\d|2[0-9])(?=\.02))\.(\d{2})\.(\d{4,})

Experiment yourself

实验自己

#3


4  

Try to use this regex:

尝试使用此正则表达式:

It works for me

这个对我有用

^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

if you are using textbox then try to use jQuery masking

如果您使用的是文本框,请尝试使用jQuery掩码