skip to Main Content

I am using jQuery datepicker to allow the user to select the dates.

var currentTime = new Date();
var startDateFrom = new Date(currentTime.getFullYear(),currentTime.getMonth()-2);
var datePickerOptions = {
    dateFormat : 'dd-MM-yy',
    monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", 
            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            changeYear : true,
        changeMonth : true,
        maxDate : '0',
        minDate : startDateFrom
}

$(document).ready(function() {
   $('#myHeader').on( 'draw.dt',   function () {  
   $(".datepickerColumn").datepicker(datePickerOptions);
});
})

I wanted to allow the user that in addition to select the date from datepicker, it can be entered manually also. Right now user is able to just enter the numbers, and no text and special characters like hyphen or slashes. Can anyone please help me with this. How can we allow to enter the date in a valid format. Thanks in advance

2

Answers


  1. I think you are looking for Autocorrection of date after entering digit.
    below is some idea. you also need to add more logic towards if day is exceeded greater than 31 or 30 and month is grater than 12.

            $(function() {
                const dateFormat = 'mm/dd/yy';
                const minDate = $.datepicker.parseDate(dateFormat, '01/01/1900');
                const maxDate = $.datepicker.parseDate(dateFormat, '12/31/2100');
    
                $('#datepicker').datepicker({
                    dateFormat: dateFormat,
                    onClose: function() {
                        correctAndFormatDate(this);
                    }
                });
    
                $('#datepicker').on('input', function() {
                    //add extra logic if it is greater than 30 for days 12 for month.
                    formatDateString(this);
                }).on('change', function() {
                    correctAndFormatDate(this);
                });
    
                function formatDateString(input) {
                    let value = input.value.replace(/[^0-9]/g, '');
                    if (value.length >= 2 && value.length <= 4) {
                        value = value.slice(0, 2) + '/' + value.slice(2);
                    } else if (value.length > 4) {
                        value = value.slice(0, 2) + '/' + value.slice(2, 4) + '/' + value.slice(4, 8);
                    }
                    input.value = value;
                }
    
                function correctAndFormatDate(input) {
                    let dateStr = $(input).val();
                    let date;
    
                    try {
                        date = $.datepicker.parseDate(dateFormat, dateStr);
                    } catch (e) {
                        alert('Invalid date format! Please enter a date in the format ' + dateFormat + '.');
                        $(input).datepicker('setDate', null);
                        return;
                    }
    
                    if (date < minDate) {
                        alert('Date corrected to minimum date.');
                        $(input).datepicker('setDate', minDate);
                    } else if (date > maxDate) {
                        alert('Date corrected to maximum date.');
                        $(input).datepicker('setDate', maxDate);
                    } else {
                        $(input).datepicker('setDate', date);
                    }
    
                    // Format the corrected date and set it back to the input field
                    dateStr = $.datepicker.formatDate(dateFormat, $(input).datepicker('getDate'));
                    $(input).val(dateStr);
                }
            });
    <!DOCTYPE html>
    <html>
    <head>
        <title>jQuery Datepicker Auto Format</title>
        <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    </head>
    <body>
        <p>Date: <input type="text" id="datepicker" maxlength="10"></p>
    </body>
    </html>
    Login or Signup to reply.
  2. In the OP you have:

    $('#myHeader').on('draw.dt', function() {...
    

    What is a "draw.dt" event? Also, this:

    $(".datepickerColumn").datepicker(datePickerOptions);
    

    should be this according to option(options):

    $(".datepickerColumn").datepicker("option", datePickerOptions);
    

    The .datepicker() doesn’t accept any input that isn’t part of it’s current dateFormat option. One way around it is to intercept any dashes the user types and change them into forward slashes.

    1. Wrap the <input> in a content element (any element with an end tag (ex. </div>)).

    2. Have that element listen for the "keydown" or "keyup" event.

    3. Make the callback function append a "/" to the <input> value whenever a "-" is keyed.

    $("input").datepicker();
    
    $(".cover").on("keydown", function(e) {
      if (e.key === "-") {
        let v = $("input").val();
        $("input").val(v + "/");
      }
    });
    <link href="https://code.jquery.com/ui/1.13.3/themes/base/jquery-ui.css" rel="stylesheet">
    
    <label class="cover">
      <input>
    </label>
    
    <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
    <script src="https://code.jquery.com/ui/1.13.3/jquery-ui.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search