Date variable cannot accept past date and needs to accept only 60days from today

Lahari532
Tera Contributor

A variable called date cannot accept past date and cant not accept today and also not accept the 10 days from today and need to accept the 60 days from today. pls provide the client script.

3 REPLIES 3

Rajesh Chopade1
Mega Sage

 

 

Hi @Lahari532 

Create onChange client script and try bellow code:

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    
    // Get the current date and time
    var currentDate = new Date();
    
    // Get the selected date from the variable
    var selectedDate = new Date(newValue);

    // Calculate the difference in days between the selected date and today
    var timeDifference = selectedDate.getTime() - currentDate.getTime();
    var dayDifference = timeDifference / (1000 * 3600 * 24);
    
    // Define the conditions
    var isPastDate = selectedDate < currentDate; // Checks if the date is in the past
    var isToday = dayDifference < 1 && dayDifference > -1; // Checks if the date is today
    var isWithin10Days = dayDifference > 0 && dayDifference <= 10; // Checks if the date is within the next 10 days
    var isAtLeast60Days = dayDifference >= 60; // Checks if the date is at least 60 days from today
    
    // Check the conditions
    if (isPastDate || isToday || isWithin10Days || !isAtLeast60Days) {
        g_form.showFieldMsg('date', 'Please select a date that is at least 60 days from today and not within the past, today, or the next 10 days.', 'error');
        //g_form.setValue('date', ''); // Clear the invalid date
    } else {
        g_form.hideFieldMsg('date', 'error');
    }
}

 

 

I hope my answer helps you to resolve your issue, if yes please mark my answer helpful and correct.

thank you

rajesh

Robbie
Kilo Patron
Kilo Patron

Hi @Lahari532,

 

This is very easily achieved using a UI Policy and the filter conditions. No scripting is required.

I provided solution to a very similar question just last week - see below link and screen shots

 

Tip: Make sure you select and update the required relative values such as the 'before' as shown below appropriate for your requirements, as when this condition is met, our script on the 'Script' tab - Execute if true field will execute.

 

To help others (or for me to help you more directly), please mark this response correct by clicking on Accept as Solution and/or Kudos.



Thanks, Robbie

 

Screenshot 2024-08-08 at 11.24.34.pngScreenshot 2024-08-08 at 11.23.55.png

Mark Roethof
Tera Patron
Tera Patron

Hi there,

 

This might help you:
- 2019-08-12 - Article - No Code date validations thru (Catalog) UI Policies

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn