Skip to content

Instantly share code, notes, and snippets.

@jacebenson
Created September 22, 2017 03:57
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jacebenson/420d0677539aeed273dccd2b1d7955e3 to your computer and use it in GitHub Desktop.
Save jacebenson/420d0677539aeed273dccd2b1d7955e3 to your computer and use it in GitHub Desktop.
Catalog Client Scripts
//Validate Date is after today
//GwtDate not available on service portal
function onSubmit() {
//Type appropriate comment here, and begin script below
//validate that the start date is before the today's date
var field = 'start_date';
var st = g_form.getValue(field);
var newTime = new GwtDate(st);
var tm = new GwtDate();
tm.now();
tm.subtractHours(24);
if (newTime.compare(tm, true) < 0) {
g_form.hideFieldMsg(field, true);
g_form.showFieldMsg(field, 'Start date must be after the today\'s date.', 'error');
return false;
}
}
//Validate Date is after set time
function onSubmit() {
var returnVal = false;
//Type appropriate comment here, and begin script below
//validate that the given field's date is at least or equal to the milleseconds to add.
var field = 'project_deadline';
var msToAdd = 1000 * 60 * 60 * 24 * 7;//ms * sec * minutes * hours * days//this is a week
var errorMsg = 'This must be at least a week out.';
/****************************************************/
/* You shouldn't have to modify anything below */
/****************************************************/
var now = new Date();
var givenDate = new Date(g_form.getValue(field));
//forwhatever reason, at this point this returns 9/24 when you select 9/25
//givenDate: Mon Sep 24 2017 19:00:00 GMT-0500 (Central Daylight Time)[1506347252815]
//when you select 9/25
givenDate.setDate(projectDeadline.getDate() + 1);//so add a day
givenDate.setHours(now.getHours());
givenDate.setMinutes(now.getMinutes());
givenDate.setSeconds(now.getSeconds());
givenDate.setMilliseconds(now.getMilliseconds());
//now returns;
//givenDate: Mon Sep 25 2017 08:47:32 GMT-0500 (Central Daylight Time)[1506347252815]
var nextWeek = new Date();
nextWeek.setTime(nextWeek.getTime() + msToAdd);
//console.log('projectDeadline: ' + projectDeadline + '[' + projectDeadline.getTime() + ']');
//console.log('weekAhead : ' + weekAhead + '[' + weekAhead.getTime() + ']');
var givenDateGreaterOrEqualToNextWeek = givenDate.getTime() >= nextWeek.getTime();
//console.log('givenDateGreaterOrEqualToNextWeek: ' + givenDateGreaterOrEqualToNextWeek);
if (givenDateGreaterOrEqualToNextWeek) {
returnVal = true;
} else {
g_form.hideFieldMsg(field, true);
g_form.showFieldMsg(field, errorMsg, 'error');
}
return returnVal;
}
//Validate Date is after variable
function onSubmit() {
//validate that the start date is before the end date
var st = getDateFromFormat(g_form.getValue("start_date_time"), g_user_date_time_format);
var et = getDateFromFormat(g_form.getValue("end_date_time"), g_user_date_time_format);
if (st > et) {
g_form.hideAllFieldMsgs();
alert("Estimated end date must be after the start date.");
g_form.showErrorBox("resource_est_end_date", "Estimated end date must be after the start date.");
return false;
}
}
//require checkboxes
function onSubmit() {
//Set the mandatory checkbox variable names and total mandatory count here
var mandatoryVars = 'option1,option2,option3,option4';
var mandatoryCount = 2;
var passed = forceMandatoryCheckboxes(mandatoryVars, mandatoryCount);
if (!passed) {
//Abort the submit
alert('You must select at least ' + mandatoryCount + ' options.');
return false;
}
}
function forceMandatoryCheckboxes(mandatory, count) {
//Split the mandatory variable names into an array
mandatory = mandatory.split(',');
var answer = false;
var varFound = false;
var numTrue = 0;
//Check each variable in the array
for (x = 0; x < mandatory.length; x++) { //Check to see if variable exists
if (g_form.getControl(mandatory[x])) {
varFound = true; //Check to see if variable is set to 'true'
if (g_form.getValue(mandatory[x]) == 'true') {
numTrue++; //Exit the loop if we have reached required number of 'true'
if (numTrue >= count) {
answer = true;
break;
}
}
}
}
//If we didn't find any of the variables allow the submit
if (varFound == false) {
answer = true;
}
//Return true or false
return answer;
}
//show field if x are chekced
/*
* Origin;
* https://community.servicenow.com/message/1025641
*/
function onChange(control, oldValue, newValue, isLoading) {
//Set the mandatory checkbox variable names and total mandatory count here
var mandatoryVars = ['option1', 'option2', 'option3', 'option4', 'option5'];
var variableToShow = 'someothervariable';
var requiredCount = 2;
var actualCount = 0;
for (var x = 0; x < mandatoryVars.length; x++) {
if (g_form.getValue(mandatoryVars[x]) == 'true') {
actualCount++;
}
}
if (requiredCount <= actualCount) {
g_form.setDisplay(variableToShow, true);
} else {
g_form.setDisplay(variableToShow, false);
}
}
//validated numbers only
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue == '') {
return;
}
var regexp = /^[0-9]*$/;
g_form.hideFieldMsg(control, true);
if (!regexp.test(newValue)) {
g_form.showFieldMsg(control, 'Only numbers allowed', 'error');
control.value = '';
}
}
//validate email
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
} else { //if newvalue is blank, set the other fields?
g_form.hideFieldMsg(control, true);
isEmailValid(control, newValue);
}
}
function isEmailValid(control, value) {
var problemMsg = isEmailValidWithReason(value);
if (problemMsg !== "") {
//jslog("isEmailValid: " + problemMsg);
g_form.showFieldMsg(control, problemMsg, 'error', true);
return false;
}
return true;
}
function isEmailValidWithReason(value) {
var localPartChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%*/?|^{}`~&'+-=_.";
var domainChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
if (value.indexOf("@") == -1)
return "missing @ sign";
var s = value.split("@");
if (s.length != 2)
return "too many at signs";
if (!containsOnlyChars(localPartChars, s[0]))
return "invalid character before the at sign";
if (s[0].length < 1)
return "at least one character must be before the at sign";
if (s[0].substr(0, 1) == ".")
return "period cannot be the first character";
if (s[0].substr(s[0].length - 1, 1) == ".")
return "period cannot be the last character before the at sign";
if (!containsOnlyChars(domainChars, s[1]))
return "invalid character after the at sign";
var periodIndex = s[1].indexOf(".");
if (periodIndex == -1)
return "missing period after the at sign";
if (periodIndex === 0)
return "period cannot be the first character after the at sign";
var periods = s[1].split(".");
var lastPeriod = periods[periods.length - 1];
if (lastPeriod.length < 1) return "must be at least 1 character after the last period"; if (!isAlphaNum(s[1].substr(0, 1))) return "the first character after the at sign must be alphanumeric"; if (!isAlphaNum(s[1].substr(s[1].length - 1, 1))) return "the last character must be alphanumeric"; return ""; } function isAlpha(thchar) { return (thchar >= 'a' && thchar <= 'z\uffff') || (thchar >= 'A' && thchar <= 'Z\uffff') || thchar == '_'; } function isAlphaNum(thchar) { return isAlpha(thchar) || isDigit(thchar); } function isDigit(thchar) { return (thchar >= '0' && thchar <= '9');
}
function containsOnlyChars(validChars, sText) {
if (!sText)
return true;
for (var i = 0; i < sText.length; i++) {
var c = sText.charAt(i);
if (validChars.indexOf(c) == -1)
return false;
}
return true;
}
//validaate phone 1
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') { //if loading, or newvalue is empty
return;
}
var n = parseInt(newValue, 10);
g_form.hideFieldMsg(control, true);
if (parseInt(newValue, 10).toString().length === 10) { //ensure its 10 numbers
var newPhone = '(' + control.value.substr(0, 3) + ')' + control.value.substr(3, 3) + '-' + control.value.substr(6, 4);
control.value = newPhone;
} else {
g_form.showFieldMsg(control, 'The phone number must be in this format: 1234567890.', 'error');
}
}
//validate phone 2
//source: https://community.servicenow.com/thread/164146
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
g_form.hideFieldMsg(control, true);
// Allows formats of (999) 999-9999, 999-999-9999, and 9999999999
var pattern = /^[(]?(\d{3})[)]?[-|\s]?(\d{3})[-|\s]?(\d{4})$/;
if (!pattern.test(newValue)) {
g_form.showFieldMsg(control, 'Phone enter a valid phone number', 'error');
control.value = '';
}
}
//validate phone 3
//source: https://community.servicenow.com/message/914311#914311
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
}
var newNum = '';
var userPhone = newValue;
userPhone = userPhone.replace(/[^\d]/g, '');
//g_form.showFieldMsg('u_telephone_number',"phone number = " + userPhone,'error');
var testDigitsPattern = /^[0-9]{10}$/;
var testResult = testDigitsPattern.test(userPhone);
//g_form.showFieldMsg('u_telephone_number',"Result = " + testResult,"error");
if (!testDigitsPattern.test(userPhone)) {
control.value = '';
g_form.showFieldMsg(control, "Invalid telephone number. Please enter your telephone number including area code.", 'error');
}
if (testDigitsPattern.test(userPhone)) {
g_form.hideFieldMsg(control, true);
newNum = '(' + userPhone.substring(0, 3) + ') ' + userPhone.substring(3, 6) + ' - ' + userPhone.substring(6, 10);
control.value = newNum;
}
}
//validate phone 4
//source: https://community.servicenow.com/message/984376#984376
function onLoad() {
var phno_ctrl = g_form.getControl('validate_phone_4');
phno_ctrl.onblur = appenddash;
}
function appenddash() {
var newPhone;
var phno = this.value;
var phoneval1 = /^\d{14}$/;
var phoneval2 = /^\d{10}$/;
g_form.hideFieldMsg(this, true);
if ((phno !== "") && !phno.match(phoneval1) && phno.length > 10) {
g_form.showFieldMsg(this, 'The phone number should be in a numbers with 14 digits if extn is available', 'error');
this.value = '';
} else {
newPhone = '(' + phno.substr(0, 3) + ')' + phno.substr(3, 3) + '-' + phno.substr(6, 4) + ' extn' + phno.substr(10, 4);
}
if ((phno !== "") && !phno.match(phoneval1) && phno.length < 10) {
g_form.showFieldMsg(this, 'The phone number should be in a numbers with 10 digits if extn is not available', 'error');
this.value = '';
} else {
newPhone = '(' + phno.substr(0, 3) + ')' + phno.substr(3, 3) + '-' + phno.substr(6, 4);
}
this.value = newPhone;
}
//validate phone 5
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
}
var tempValue = newValue;
//Use Regular Expressions to verify number
var phoneRegex1 = /^\d{3}-\d{3}-\d{4}$/;
var phoneRegex2 = /^(800|866|877)/;
var phoneRegex3 = /^(1{3}-1{3}-1{4}|2{3}-2{3}-2{4}|3{3}-3{3}-3{4}|4{3}-4{3}-4{4}|5{3}-5{3}-5{4}|6{3}-6{3}-6{4}|7{3}-7{3}-7{4}|8{3}-8{3}-8{4}|9{3}-9{3}-9{4}|0{3}-0{3}-0{4})$/;
g_form.hideFieldMsg(control, true);
if (tempValue.match(phoneRegex1) && !tempValue.match(phoneRegex2) && !tempValue.match(phoneRegex3)) {
return;
} else {
control.value = '';
g_form.showFieldMsg(control, 'Phone number must be in format XXX-XXX-XXXX and must not start with 800, 866, or 877.', 'error', true);
}
}
//validate phone 6
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') { //if loading, or newvalue is empty
return;
}
var n = parseInt(newValue, 10);
var newPhone;
g_form.hideFieldMsg(control, true);
if (parseInt(newValue, 10).toString().length === 4) { //ensure its 10 numbers
newPhone = 'EXT ' + control.value;
control.value = newPhone;
} else if (parseInt(newValue, 10).toString().length === 10) { //ensure its 10 numbers
newPhone = '(' + control.value.substr(0, 3) + ')' + control.value.substr(3, 3) + '-' + control.value.substr(6, 4);
control.value = newPhone;
} else {
g_form.showFieldMsg(control, 'The phone number must be in this format: 1234567890 or 1234', 'error');
}
}
//set place holder
//this is unnecessary in Jakarta see https://servicenow.implementation.blog/great-ui-trick-html-placeholders/
function onLoad() {
u_addPlaceholderAttribute('user','Someones name goes here');
}
function u_addPlaceholderAttribute(variableName, hint) {
try {
var fieldName = g_form.getControl(variableName).name.toString();
if (Prototype.Browser.IE) {
fieldName.placeholder = hint;
} else {
$(fieldName).writeAttribute('placeholder', hint);
}
} catch (err) {}
}
//make variables read only
function onLoad() {
try {
//Get the 'Variables' section
var ve = $('variable_map').up('table');
//Disable all elements within with a class of 'cat_item_option'
ve.select('.cat_item_option', '.slushselectmtm', '.questionsetreference').each(function (elmt) {
elmt.disabled = true;
});
//Remove any reference or calendar icons
ve.select('img[src*=reference_list.gifx]', 'img[src*=small_calendar.gifx]').each(function (img) {
img.hide();
});
//Hide list collector icons
ve.select('img[src*=arrow]').each(function (img) {
img.up('table').hide();
});
} catch (e) {}
}
//flash variable
function flashVar(v) {
g_form.nameMap.map(function (rec) {
if (rec.prettyName === v) {
g_form.flash("ni.VE" + rec.realName, "#FFFACD", 0)
}
});
}
flashVar('server_decom_prepinfo');
//require attachment
function onSubmit() {
'use strict';
var attachment = new GlideRecord("sys_attachment");
attachment.addQuery("table_name", "sc_cart_item");
attachment.addQuery("table_sys_id", gel('sysparm_item_guid').value);
attachment.query();
if (!attachment.hasNext()) {
alert("You must attach your public SSH Key. Please see instructions for more information.");
return false;
}
}
//ser server fields
function onChange(control, oldValue, newValue, isLoading) {
try {
g_form.clearValue('server_ip');
g_form.clearValue('environment');
g_form.getReference('server', function(server){
g_form.setValue('server_ip', server.ip_address);
g_form.setValue('environment', server.u_env_list);
});
} catch(error) {
console.log(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment