Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bootstrap validation date DD.MM.YYYY jquery

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:

/(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")

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.

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>
like image 372
Stefan0309 Avatar asked May 11 '16 19:05

Stefan0309


3 Answers

First try is always \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)$

It still has false positives with like 31.02.1999 dates

like image 68
vp_arth Avatar answered Nov 12 '22 00:11

vp_arth


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 ():

(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

like image 45
ndnenkov Avatar answered Nov 12 '22 02:11

ndnenkov


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

like image 4
Anurag Kumar Avatar answered Nov 12 '22 00:11

Anurag Kumar