sp-date-picker input text box readonly

Deep4
Tera Contributor

I have <sp-date-picker>from which I am setting min and max date, and its working fine but if user select date manually from text box it gives access to set any date. 
But I want restrict it either by adding error message or by making input box as readonly.

Please help.

2 REPLIES 2

Bhavya11
Kilo Patron

Hi @Deep4 

 

you can use Date field type or variable type to avoid the scripting

otherwise right on change Client script on field and write below code

 

    // Regular expression to validate date format (MM/DD/YYYY)
    var dateFormat = /^(0[1-9]|1[0-2])\/(0[1-9]|[12][0-9]|3[01])\/\d{4}$/;

    // Check if the date matches the format
    if (!dateFormat.test(newValue)) {
        // If the date is invalid, display an error message
        g_form.showFieldMsg('date', 'Please enter a valid date in MM/DD/YYYY format', 'error');
        return;
    }

    // Split the date into its components
    var dateParts = newValue.split('/');
    var month = parseInt(dateParts[0], 10);
    var day = parseInt(dateParts[1], 10);
    var year = parseInt(dateParts[2], 10);

    // Check for logical date correctness
    if (!isValidDate(month, day, year)) {
        g_form.showFieldMsg('date', 'Please enter a valid date', 'error');
        return;
    }

    // Check if the date is in the past
    var today = new Date();
    today.setHours(0, 0, 0, 0); // Set time to the start of the day
    var inputDate = new Date(year, month - 1, day);

    if (inputDate < today) {
        g_form.showFieldMsg('date', 'The date cannot be in the past', 'error');
    } else {
        // Remove any error message if the date is valid
        g_form.hideFieldMsg('date');
    }

    function isValidDate(month, day, year) {
        // Check for leap year
        var isLeapYear = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);

        // Days in each month
        var daysInMonth = [31, (isLeapYear ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        // Check if day is valid for the given month
        return day > 0 && day <= daysInMonth[month - 1];
    }

 


output 

Bhavya11_0-1721040775249.pngBhavya11_1-1721040786816.png

 

Bhavya11_2-1721040803271.png 

Bhavya11_3-1721040873095.png

 

If my response proves useful, please indicate its helpfulness by selecting "Accept as Solution" and " Helpful."

 

 

Thanks,

BK

Deep4
Tera Contributor

Hi  ,

Thanks for your reply. 

But in my case I have HTML code to create date field form which I am setting the min and max date. And I just want to restrict user from entering manual date in input area.
Below is my HTML code:

 

<sp-date-picker  field="fromdate" id="custData" sn-min-date="min" sn-max-date="max" readonly></sp-date-picker>