How to restrict past and future Date using Business rules

sushma9
Tera Contributor

Hi All,

 I am trying to restrict the past Date using the BR but i am not able to do it and getting the error .Can any one help me on this . Let me know if any modifications  has to be done in the Code 

Script :

 var arrival = new GlideDate((current.u_arrival_date);
        var dep = new GlideDate((current.u_departure_date);
        var arrivalFinal = arrival.getDate();
        var depFinal = dep.getDate();
        if (depFinal.compareTo(arrivalFinal) = -1) {
            gs.addErrorMessage(" You have Selected the Past Date . Kindly  select the Future Date ");
            current.setAbortAction(true);
        } else If (depFinal.compareTo(arrivalFinal )= 0)) {
            gs.addInfoMessage(" You have Selected the todays Date . Kindly  Please confirm to submit the request ");
return confirm ();
}else  (depFinal.compareTo(arrivalFinal )= 1)) {
gs.addInfoMessage(" Record has been created");
}
1 ACCEPTED SOLUTION

Kalyani Jangam1
Mega Sage
Mega Sage

Hi @sushma9 

 

First thing ((current.u_arrival_date), there is extra braces '(' you used.

second thing compareTo is generally used in string type and date not in string it is object

 

you can use code like below, if comparision on today

 

var dateField = new GlideDateTime(current.u_arrival_date);;

var nowTime = new GlideDateTime(); // current date and time

var dur = new GlideDuration();

dur = GlideDateTime.subtract(dateField, nowTime);

var days = dur.getDayPart();

gs.info(days);

if(days>0){
gs.info("Arrival date can not be in past");

}

 

Please check and Mark Helpful or correct if it really helps you.

View solution in original post

11 REPLIES 11

Hi  Ankur,

 I tried with Client scripts and its working fine for me  but i want to try with BR and How to validate .Can you please check my code let me know what is the mistake i have done.

sadif_raja
Tera Guru

Best Solution : 

Using Native JavaScript Date Methods for Date Validation in ServiceNow

In ServiceNow, you can validate date fields without relying on external libraries like moment.js by using JavaScript's built-in Date methods. This solution works natively and simplifies date handling for form submissions.

Here’s how you can implement the solution to validate that the difference between two dates (u_from and u_to) does not exceed six months.

Steps:

  1. Retrieve Date Values: Use g_form.getValue() to fetch the values from your date fields (u_from and u_to).

  2. Parse the Date Values: Use JavaScript's Date object to convert the string values from the form fields into actual date objects.

  3. Calculate the Difference in Months: You can calculate the difference in months by comparing the year and month values from both dates. This approach does not require any external library and works efficiently.

  4. Add Validation Logic: Check if the calculated difference in months exceeds six. If it does, display an error message using g_form.addErrorMessage() and prevent the form from being submitted.

Here’s the updated code:

function onSubmit() {
// Get the values of the date fields
var startDate = g_form.getValue('u_from'); // Replace with your actual field name
var endDate = g_form.getValue('u_to'); // Replace with your actual field name

// Ensure both dates are filled
if (!startDate || !endDate) {
g_form.addErrorMessage('Please enter both start and end dates.');
return false;
}

// Parse dates using JavaScript's Date object
var start = new Date(startDate);
var end = new Date(endDate);

// Calculate the difference in months
var diffInMonths = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth());

// Check if the difference is 6 months
if (Math.abs(diffInMonths) >= 6) {
g_form.addErrorMessage('The gap between the dates should not exceed 6 months.');
return false; // Cancel form submission
}

return true; // Allow form submission
}

 

Explanation:

  • Date Parsing: new Date(startDate) and new Date(endDate) convert the form input values into Date objects.
  • Month Difference Calculation: (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth()) calculates the difference in months by comparing both the year and month values.
  • Validation: If the difference is 6 months or greater, an error message is displayed, and the form submission is canceled.

Why Use This Solution?

  • No External Dependencies: This method doesn’t require moment.js or any external libraries, making it lightweight and efficient.
  • Native JavaScript: It leverages built-in JavaScript functionality, ensuring compatibility with ServiceNow’s scripting environment.

This approach is clean, efficient, and works directly within the ServiceNow platform. 
Mark it helpful, if you find the solution as the best one!