Validate Date field on the form after fetching from the script
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
3 hours ago
Hi Community people,
I have a field called "Request is existing or new?" on the catalog form and it has 2 values i.e., New and Existing.
1.If a user selects 'New' option then all the fields like planned start date , planned end date will appear with empty values. So if a user changes anything on the planned start end date, I wrote a validation script(onchange script) that it will not allow to select a date which is less than 20 days from today's date and it will clears the value if the date is less than 20 days.
2. if a user selects 'Existing ' option then all the fields like planned start date , planned end date are populated with exiting values of a request. But the planned start date is also getting cleared if the date is less than 20 days. I don't want that, whatever the value is there while fetching it should be there in planned start date and if user changes anything on planned start date then on change should be triggered?
Any suggestions or workaround?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
6m ago - last edited 2m ago
Create a new Script Include, check the Client callable checkbox, and paste this code:
var DateValidationUtils = Class.create();
DateValidationUtils.prototype = Object.extendsObject(AbstractScriptProcessor, {
validateDateRange: function() {
var selectedDateStr = this.getParameter('sysparm_selected_date');
var now = new GlideDateTime();
var selectedDate = new GlideDateTime(selectedDateStr);
// Add 20 days to current system time
now.addDaysLocalTime(20);
// Return invalid if the date is less than 20 days from today
if (selectedDate.getNumericValue() < now.getNumericValue()) {
return 'invalid';
}
return 'valid';
},
type: 'DateValidationUtils'
});
Step 02: Update your onChange Client Script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
// 1. Prevents execution during initial fetch/load or if field is cleared
if (isLoading || newValue === '' || newValue == oldValue) {
return;
}
// 2. Call the server script to validate the date
var ga = new GlideAjax('DateValidationUtils');
ga.addParam('sysparm_name', 'validateDateRange');
ga.addParam('sysparm_selected_date', newValue);
ga.getXMLAnswer(function(response) {
if (response === 'invalid') {
g_form.clearValue(control.name); // Clears the field automatically
alert('The selected date must be at least 20 days from today.');
}
});
}
Helpful? Please mark the response as Accepted Solution ✅ and close the thread — this helps future readers find the solution faster.
Regards,
Sachinvic
✨ArchX Certified | ✨16x ServiceNow AI MVP
