Join us Dec. 16 for The Community Hour, our first global virtual User Group event!

onSubmit client script with asynchronous GlideAjax postal-code validation does not resubmit the form

Prithvi Ramesh1
Mega Sage

Here’s a detailed ServiceNow Community post you can use. Fill in the bracketed details before posting.

Title:
onSubmit client script with asynchronous GlideAjax postal-code validation does not resubmit the form

Post:
I’m trying to validate a postal code before allowing a ServiceNow form/catalog request to submit. The client script calls a Script Include using GlideAjax, holds the initial submission by returning false, and then attempts to resubmit after the callback returns.

The flow is:

  1. Read the country and postal-code fields.
  2. Skip validation if either field is blank or if the exact values were already validated.
  3. Set a validation flag to IN_PROGRESS while the GlideAjax call runs.
  4. If the server response is valid, store a key for the validated country/postal-code pair and call gsf...
  5. If invalid, show a field-level error and keep the form from submitting.

Issue:
The script is not working as expected. Specifically, [describe what happens: the form submits without validation / remains stuck / validation runs but does not resubmit / an error appears]. The browser console shows [paste the exact error, if any].

Expected behavior:
The form should remain unsubmitted while validation is running, display an error if the postal code is invalid, and submit the original action (such as Order Now or Add to Cart) once validation succeeds.

Environment:

Could someone advise whether this asynchronous onSubmit and resubmission pattern is supported in this interface, and what the recommended approach is? I’m particularly unsure whether gsftSubmit and g_form.getActionName() are appropriate for the interface and form type I’m using.

Troubleshooting details to include if available:
Please also note whether the GlideAjax callback runs, what answer contains, and whether postal_validated is an actual field/variable on the form. Those details can help distinguish a server-response issue from a resubmission or client-script compatibility issue.

function onSubmit() {
    var COUNTRY_FIELD = 'country1';
    var POSTAL_FIELD = 'postal_code1';
    var FLAG_FIELD = 'postal_validated';
    var country = g_form.getValue(COUNTRY_FIELD);
    var postalCode = g_form.getValue(POSTAL_FIELD);
    if (!country || !postalCode) {
        return true;
    }
    // Already validated for exactly these values -> let the submit through
    var currentKey = country + '|' + postalCode;
    if (g_form.getValue(FLAG_FIELD) === currentKey) {
        return true;
    }
    // A validation call is already running -> keep the form held
    if (g_form.getValue(FLAG_FIELD) === 'IN_PROGRESS') {
        return false;
    }
    g_form.setValue(FLAG_FIELD, 'IN_PROGRESS');
    // Capture the clicked button (Order Now / Add to Cart) before the async call
    var actionName = g_form.getActionName();
    var ga = new GlideAjax('PostalCodeValidator');
    ga.addParam('sysparm_name', 'validatePostalCode');
    ga.addParam('sysparm_country', country);
    ga.addParam('sysparm_postal_code', postalCode);
    ga.getXMLAnswer(function(answer) {
        try {
            var result = JSON.parse(answer);
            g_form.hideFieldMsg(POSTAL_FIELD, true);
            if (!result.valid) {
                g_form.setValue(FLAG_FIELD, '');
                g_form.showFieldMsg(POSTAL_FIELD, result.message, 'error');
                return;
            }
            // Store the validated values, then re-submit
            g_form.setValue(FLAG_FIELD, currentKey);
            gsftSubmit(null, g_form.getFormElement(), actionName);
        } catch (e) {
            console.log(answer);
            console.log(e);
            g_form.setValue(FLAG_FIELD, '');
            g_form.showFieldMsg(POSTAL_FIELD, 'Unable to validate postal code.', 'error');
        }
    });
    return false; // hold the submit until the server answers
}
1 REPLY 1

Tarun Rekandar
Giga Guru

Hi @Prithvi Ramesh1,

 

The Problem is that postal_validated most likely isn’t a real form field, so setValue does nothing and onSubmit never sees the “validated” flag. After gsftSubmit fires, the script validates again and returns false in an endless loop. Also, gsftSubmit and getActionName() work only in the classic UI. Fix: store the flag in a JavaScript variable instead of a form field, and confirm which interface you’re using.

 

onSubmit client script:

// ---- State lives in JS variables (page-lifetime), NOT in a form field ----
var postalValidatedKey = '';     // "country|postal" that already passed validation
var postalValidating   = false;  // true while GlideAjax call is running

function onSubmit() {
    var COUNTRY_FIELD = 'country1';       // <-- your field/variable name
    var POSTAL_FIELD  = 'postal_code1';   // <-- your field/variable name

    var country    = g_form.getValue(COUNTRY_FIELD);
    var postalCode = g_form.getValue(POSTAL_FIELD);

    // 1. Nothing to validate -> let the form submit
    if (!country || !postalCode) {
        return true;
    }

    // 2. Exactly these values were already validated -> let the form submit
    var currentKey = country + '|' + postalCode;
    if (postalValidatedKey === currentKey) {
        return true;
    }

    // 3. A call is already running -> keep the form held
    if (postalValidating) {
        return false;
    }

    // 4. Start validation
    postalValidating = true;

    // Capture the clicked button (Order Now / Add to Cart / Submit / Save) BEFORE the async call
    var actionName = '';
    try {
        actionName = g_form.getActionName();
    } catch (ignore) {}

    var ga = new GlideAjax('PostalCodeValidator');
    ga.addParam('sysparm_name', 'validatePostalCode');
    ga.addParam('sysparm_country', country);
    ga.addParam('sysparm_postal_code', postalCode);

    ga.getXMLAnswer(function(answer) {
        postalValidating = false;

        var result;
        try {
            result = JSON.parse(answer);
        } catch (e) {
            console.log('PostalCode validation: bad server answer ->', answer, e);
            g_form.showFieldMsg(POSTAL_FIELD, 'Unable to validate postal code.', 'error');
            return;
        }

        g_form.hideFieldMsg(POSTAL_FIELD, true);

        if (!result || !result.valid) {
            postalValidatedKey = '';
            g_form.showFieldMsg(POSTAL_FIELD,
                (result && result.message) || 'Invalid postal code.', 'error');
            return;
        }

        // Valid: remember the pair, then re-submit the original action
        postalValidatedKey = currentKey;
        resubmitForm(actionName);
    });

    return false; // hold the submit until the server answers
}

/**
 * Re-submits the form using whatever the current UI supports.
 */
function resubmitForm(actionName) {
    try {
        if (typeof gsftSubmit === 'function') {
            // Classic UI (forms and catalog items)
            // Fallback ids: standard form save = 'sysverb_insert' / 'sysverb_update'
            // Catalog "Order Now" is usually 'sysverb_ws_save', "Add to Cart" 'sysverb_ws_add_to_cart'
            // (verify in browser dev tools on your instance)
            gsftSubmit(null, g_form.getFormElement(), actionName || 'sysverb_insert');
        } else if (typeof g_form.submit === 'function') {
            // Service Portal / Workspace
            g_form.submit(actionName || undefined);
        } else {
            console.log('No supported resubmit API found in this interface.');
            g_form.addErrorMessage('Validated, but please click Submit again.');
        }
    } catch (e) {
        console.log('Resubmit failed:', e);
        g_form.addErrorMessage('Validated, but please click Submit again.');
    }
}

/*
 * NOTES
 * -----
 * 1. If the user edits country/postal after a successful validation,
 *    currentKey differs from postalValidatedKey, so it re-validates. Good.
 * 2. Service Portal: if g_form.submit() does not trigger the right action on your
 *    release, switch to the onChange pattern: run GlideAjax in onChange of the
 *    country/postal fields, store the result in a variable, and make onSubmit
 *    a purely synchronous check (return false + g_form.addErrorMessage if invalid).
 * 3. Debug: console.log('callback', answer) at the top of the callback to confirm
 *    the callback fires and what 'answer' contains.
 */

 

scriptinclude:

 

var PostalCodeValidator = Class.create();
PostalCodeValidator.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {

    // Country (ISO-2 code OR display name, lower-cased) -> regex.
    // Adjust to match the values stored in your country field.
    PATTERNS: {
        'in': /^[1-9][0-9]{5}$/,                                   // India: 6 digits
        'india': /^[1-9][0-9]{5}$/,
        'us': /^\d{5}(-\d{4})?$/,                                  // USA: 12345 or 12345-6789
        'united states': /^\d{5}(-\d{4})?$/,
        'gb': /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i,              // UK
        'united kingdom': /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i,
        'ca': /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/i,                        // Canada
        'canada': /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/i,
        'de': /^\d{5}$/,                                           // Germany
        'germany': /^\d{5}$/
    },

    validatePostalCode: function() {
        var country = (this.getParameter('sysparm_country') || '').toString().trim();
        var postal  = (this.getParameter('sysparm_postal_code') || '').toString().trim();
        var result  = { valid: true, message: '' };

        try {
            var pattern = this.PATTERNS[country.toLowerCase()];

            if (!pattern) {
                // Unknown country: do not block the user.
                // Change to valid:false if you want to be strict.
                result.valid = true;
            } else if (!pattern.test(postal)) {
                result.valid = false;
                result.message = 'Invalid postal code for ' + country + '.';
            }
        } catch (e) {
            gs.error('PostalCodeValidator error: ' + e);
            result.valid = false;
            result.message = 'Postal code validation failed on the server.';
        }

        // MUST be a JSON string; the client does JSON.parse(answer)
        return JSON.stringify(result);
    },

    type: 'PostalCodeValidator'
});

 

Accept the solution if it assisted you with your question & Mark this response as Helpful.

 

Regards,
Tarun